如何使用jquery选择包含特定文本值的跨度

How do I select a span containing a specific text value, using jquery?

本文关键字:文本 何使用 jquery 选择 包含特      更新时间:2023-09-26

如何查找包含文本"find ME"的span

<div>
   <span>FIND ME</span>
   <span>dont find me</span>
</div>

http://api.jquery.com/contains-selector/

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

ETA:

contains选择器很好,但过滤跨度列表可能会更快: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

使用包含:

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

顺便说一句,如果你想将其与变量一起使用,你可以这样做:

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
        });
     }
}

我认为这将适用于

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