如何找到包含文本的跨度 “FIND ME”如何使用jquery选择包含特定文本值的跨度?
<div>
<span>FIND ME</span>
<span>dont find me</span>
</div>
如何找到包含文本的跨度 “FIND ME”如何使用jquery选择包含特定文本值的跨度?
<div>
<span>FIND ME</span>
<span>dont find me</span>
</div>
http://api.jquery.com/contains-selector/
$("span:contains('FIND ME')")
ETA:
的包含选择是好的,但过滤跨度的列表,如果可能更快:http://jsperf.com/jquery-contains-vs-filter
$("span").filter(function() { return ($(this).text().indexOf('FIND ME') > -1) }); -- anywhere match
$("span").filter(function() { return ($(this).text() === 'FIND ME') }); -- exact match
这是否回答我的下一个问题? http://stackoverflow.com/questions/9424509/how-do-i-select-a-span-containing-an-exact-text-value-using-jquery – MedicineMan 2012-02-24 02:27:49
是的。过滤器再次是答案,但是这次您检查整个.text()值以进行匹配,而不是查找索引。答案已更新。 – Malk 2012-02-24 02:31:20
谢谢Malk!我没有听说过滤器()。有时候这是必要的,因为contains()是通配符比较,因此如果需要精确匹配,将会找到'FIND ME'和'DO NOT FIND ME',这对您无用。 – Peadar 2013-01-14 11:17:59
使用contains:
$("span:contains('FIND ME')")
我认为这会工作
var span;
$('span').each(function(){
if($(this).html() == 'FIND ME'){
span = $(this);
}
});
Oh yeah。那些其他答案要好得多。使用这些。 – buck54321 2012-02-24 02:17:02
顺便说一句,如果你想用一个变量使用这个,你会做这种方式:
function findText() {
$('span').css('border', 'none'); //reset all of the spans to no border
var find = $('#txtFind').val(); //where txtFind is a simple text input for your search value
if (find != null && find.length > 0) {
//search every span for this content
$("span:contains(" + find + ")").each(function() {
$(this).css('border', 'solid 2px red'); //mark the content
});
}
}
可能重复的[jQuery查找元素的文本](http://stackoverflow.com/questions/7321896/jquery-find-element-by-text) – 2012-02-24 03:17:16