I'm using the following code to create fractions:
<script type='text/javascript'>
$(document).ready(function () {
$('.fraction').each(function(key, value) {
$this = $(this)
var split = $this.html().split("/")
if( split.length == 2 ){
$this.html('<span class="top">'+split[0]+'</span><span class="bottom">'+split[1]+'</span>')
}
});
});
</script>
If I have the following code in my body, it successfully formats as a fraction:
<span class="fraction">4/1</span>
If, however, I include a tag, as illustrated below, the function no longer works
<span class="fraction"><strike>4</strike>/1</span>
How can I fix this? Thanks!
Use .text()
to strip away the html tags and just get the text.
var split = $this.text().split("/")
If you want to keep the html markup in your result, an easy solution would be to use a different delimiter for your fraction, like a double slash //
, a backslash \\
, or a pipe |
. JSFiddle
Using this answer you could also use regex to verify that it only splits if the character isn't found inside <..>
. JSFiddle
var split = $this.html().split(/\/(?=[^>]*(?:<|$))/)
If you want to do it correctly (while preserving your markup), it gets a bit complicated due to the fact that you need a slash that is in a text node that is a direct child of the .fraction
element; and jQuery doesn't deal with text nodes well. So:
$(function() { $('.fraction').each(function(_, e) { var offset = 0, html = '<span class="top">', found = false; $.each(e.childNodes, function(_, c) { if (c.nodeType == Node.TEXT_NODE) { if (m = c.textContent.match(/(.*)\\/(.*)/)) { found = true; html += m[1] + '</span>/<span class="bottom">' + m[2]; } else { html += c.textContent; } } else { html += c.outerHTML; }; }); if (found) { e.innerHTML = html + '</span>'; } }); });
.top { color: red; } .bottom { color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="fraction"><strike>1</strike>/2</span> <span class="fraction">2/2</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.