2012-02-24 30 views

回答

73

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 
+2

这是否回答我的下一个问题? 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

+0

是的。过滤器再次是答案,但是这次您检查整个.text()值以进行匹配,而不是查找索引。答案已更新。 – Malk 2012-02-24 02:31:20

+0

谢谢Malk!我没有听说过滤器()。有时候这是必要的,因为contains()是通配符比较,因此如果需要精确匹配,将会找到'FIND ME'和'DO NOT FIND ME',这对您无用。 – Peadar 2013-01-14 11:17:59

9

使用contains

$("span:contains('FIND ME')") 
2

我认为这会工作

var span; 
$('span').each(function(){ 
    if($(this).html() == 'FIND ME'){ 
    span = $(this); 
    } 
}); 
+1

Oh yeah。那些其他答案要好得多。使用这些。 – buck54321 2012-02-24 02:17:02

1

顺便说一句,如果你想用一个变量使用这个,你会做这种方式:

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 
     }); 
    } 
} 
相关问题