如何使用jquery选择包含特定文本值的范围?

时间:2022-10-31 17:52:21

How do I find the span containing the text "FIND ME"

如何找到包含文本“查找我”的范围

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

4 个解决方案

#1


80  

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

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

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

ETA:

ETA:

The contains selector is nice, but filtering a list of spans if probably quicker: http://jsperf.com/jquery-contains-vs-filter

包含选择器很好,但如果可能更快,则过滤一个跨度列表: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


9  

Use contains:

使用包含:

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

#3


3  

I think this will work

我认为这会奏效

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

#4


2  

By the way, if you'd like to use this with a variable, you'd do it this way:

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

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

#1


80  

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

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

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

ETA:

ETA:

The contains selector is nice, but filtering a list of spans if probably quicker: http://jsperf.com/jquery-contains-vs-filter

包含选择器很好,但如果可能更快,则过滤一个跨度列表: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


9  

Use contains:

使用包含:

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

#3


3  

I think this will work

我认为这会奏效

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

#4


2  

By the way, if you'd like to use this with a variable, you'd do it this way:

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

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