问题
I'm just wondering if there's a way to locate numbers on a page with jQuery or plain Javascript.
Here's what I want to do:
Say "June 23" is on the page. What I want to do is be able to prepend and append some <span>
selectors to the number.
Using :contains()
with jQuery selects the whole thing, not just the number.
These strings are being generated without any wrapping elements by a Wordpress theme I'm working on, and I only want to select the number.
Any help would be appreciated! Thanks for even thinking about it.
-George
回答1:
You can walk through all the elements, looking at text nodes, and replacing them with updated content that has the number wrapped.
var regex = /(\d+)/,
replacement = '<span>$1</span>';
function replaceText(el) {
if (el.nodeType === 3) {
if (regex.test(el.data)) {
var temp_div = document.createElement('div');
temp_div.innerHTML = el.data.replace(regex, replacement);
var nodes = temp_div.childNodes;
while (nodes[0]) {
el.parentNode.insertBefore(nodes[0],el);
}
el.parentNode.removeChild(el);
}
} else if (el.nodeType === 1) {
for (var i = 0; i < el.childNodes.length; i++) {
replaceText(el.childNodes[i]);
}
}
}
replaceText(document.body);
Example: http://jsfiddle.net/JVsM4/
This doesn't do any damage to existing elements, and their associated jQuery data.
EDIT: You could shorten it a bit with a little jQuery:
var regex = /(\d+)/g,
replacement = '<span>$1</span>';
function replaceText(i,el) {
if (el.nodeType === 3) {
if (regex.test(el.data)) {
$(el).replaceWith(el.data.replace(regex, replacement));
}
} else {
$(el).contents().each( replaceText );
}
}
$('body').each( replaceText );
Example: http://jsfiddle.net/JVsM4/1/
Note that the regex requires the g
global modifier.
Probably a little slower this way, so if the DOM is quite large, I'd use the non-jQuery version.
回答2:
Just thinking out loud, but do you reckon this would work?
document.body.innerHTML = document.body.innerHTML.replace(/(\d+)/g, "<span class='number'>$1</span>")
回答3:
It is fully dependent on what format your date is.
I found this website with a lot of different regular expressions (because you are just searching a normal piece of text for a date).
This seems a good option if this is your format for your date (dd MMM yyyy): http://regexlib.com/REDetails.aspx?regexp_id=405
I assume, because it is a template, that your dates will be the same for all pages. So the format will be the same as well. You can use the regular expression on every piece of text on your template if you define it well.
来源:https://stackoverflow.com/questions/6480798/select-numbers-on-a-page-with-jquery-or-javascript