jquery , selector, contains one of the text
I need a help for one thing :
this is my jQuery idea:
var text = "Some Text1, Some Text2, Some Text3";
$("h3:contains('"+even one of this string+"')").each(function() {
$(this).append("<span>Some Text</span>");
});
This is My HTML
<h3 class="test1">Some Text2</h3>
<h3 class="test1">Some Text1</h3>
<h3 class="test3">Another Text</h3>
What I want in OUTPUT:
<h3 class="test1">
Some Text2
<span>开发者_运维百科;Some Text</span>
</h3>
<h3 class="test1">
Some Text1
<span>Some Text</span>
</h3>
<h3 class="test3">Another Text</h3>
Thanks!
quick jQuery
var text = "Some Text1, Some Text2, Some Text3";
$(document).ready(function(){
$(text.split(", ")).each(function(i,v){
$('h3:contains("'+ v +'")').append('<span>Some text</span>');
})
})
quick demo
var text = "Some Text1, Some Text2, Some Text3";
var aText = text.split(","); //splits into array on comma delimiter
for (var i = 0; i < aText.length; i++) {
$("h3:contains('" + aText[i] + "')").each(function() {
$(this).append("<span>Some Text</span>");
});
}
This ought to work for you (but unclear if you can break in/out of the selector string like that. Let me know if it's good.
Just iterate through the headings and do a regexp match on $(this).text(). You can even make this into a custom selector if you really want:
$.extend($.expr[':'], {
matches: function(node, index, args, stack) {
var re = new RegExp(args[3]);
return !!$(node).text().match(re);
}
});
$(function() {
$('h3:matches("Some Text[123]")').each(function() {
$(this).append("<span>Some Text</span>");
});
});
You want:
$("h3:contains('Some Text1'), h3:contains('Some Text2'), h3:contains('Some Text3')").each(function() {
$(this).append("<span>Some Text</span>");
});
EDIT
In response to OP comment, note, you can do the following:
var text = "Some Text1, Some Text2, Some Text3";
text.replace(/\s?([^,]+?)(,)|\s([^,]+?)$/g, "h3:contains('$1$3')$2");
To generate your element list.
Then you do:
var text = "Some Text1, Some Text2, Some Text3";
text.replace(/\s?([^,]+?)(,)|\s([^,]+?)$/g, "h3:contains('$1$3')$2");
$(text).each(function() {
$(this).append("<span>Some Text</span>");
});
This will replace all of the comma separated terms by the term itself surrounded by h3:contains(' and '). These will be separated by commas in the same manner as the original string.
The simple solution if you know your strings ahead of time would be to use multiple selectors like so:
$("h3:contains('Some Text1'), h3:contains('Some Text2'), h3:contains('Some Text3')").each(function() {
$(this).append("<span>Some Text</span>");
});
精彩评论