使用 jQuery 查找文本字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/926580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:08:39  来源:igfitidea点击:

Find text string using jQuery?

jquerytext

提问by Keith Donegan

Say a web page has a string such as "I am a simple string" that I want to find. How would I go about this using JQuery?

假设一个网页有一个我想要查找的字符串,例如“我是一个简单的字符串”。我将如何使用 JQuery 解决这个问题?

回答by Tony Miller

jQuery has the contains method. Here's a snippet for you:

jQuery 有 contains 方法。这是给你的一个片段:

<script type="text/javascript">
$(function() {
    var foundin = $('*:contains("I am a simple string")');
});
</script>

The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/

上面的选择器选择包含目标字符串的任何元素。foundin 将是一个包含任何匹配元素的 jQuery 对象。API信息见:https: //api.jquery.com/contains-selector/

One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')

使用“*”通配符需要注意的一件事是您将获得所有元素,包括您可能不想要的 html 和 body 元素。这就是为什么 jQuery 和其他地方的大多数示例都使用 $('div:contains("I am a simple string")')

回答by BarelyFitz

Normally jQuery selectors do not search within the "text nodes" in the DOM. However if you use the .contents() function, text nodes will be included, then you can use the nodeType property to filter only the text nodes, and the nodeValue property to search the text string.

通常,jQuery 选择器不会在 DOM 中的“文本节点”内进行搜索。但是,如果您使用 .contents() 函数,将包含文本节点,那么您可以使用 nodeType 属性仅过滤文本节点,并使用 nodeValue 属性搜索文本字符串。

    $('*', 'body')
        .andSelf()
        .contents()
        .filter(function(){
            return this.nodeType === 3;
        })
        .filter(function(){
            // Only match when contains 'simple string' anywhere in the text
            return this.nodeValue.indexOf('simple string') != -1;
        })
        .each(function(){
            // Do something with this.nodeValue
        });

回答by Slim

This will select just the leaf elements that contain "I am a simple string".

这将仅选择包含“我是一个简单字符串”的叶元素。

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).css("border","solid 2px red") });

Paste the following into the address bar to test it.

将以下内容粘贴到地址栏中进行测试。

javascript: $('*:contains("I am a simple string")').each(function(){ if($(this).children().length < 1) $(this).css("border","solid 2px red") }); return false;

If you want to grab just "I am a simple string". First wrap the text in an element like so.

如果你只想抓住“我是一个简单的字符串”。首先将文本包裹在这样的元素中。

$('*:contains("I am a simple string")').each(function(){
     if($(this).children().length < 1) 
          $(this).html( 
               $(this).text().replace(
                    /"I am a simple string"/
                    ,'<span containsStringImLookingFor="true">"I am a simple string"</span>' 
               )  
           ) 
});

and then do this.

然后这样做。

$('*[containsStringImLookingFor]').css("border","solid 2px red");

回答by nickf

If you just want the node closest to the text you're searching for, you could use this:

如果您只想要最接近您要搜索的文本的节点,则可以使用以下命令:

$('*:contains("my text"):last');

This will even work if your HTML looks like this:

如果您的 HTML 如下所示,这甚至会起作用:

<p> blah blah <strong>my <em>text</em></strong></p>

Using the above selector will find the <strong>tag, since that's the last tag which contains that entire string.

使用上面的选择器将找到<strong>标签,因为这是包含整个字符串的最后一个标签。

回答by Chris Doggett

Take a look at highlight(jQuery plugin).

看看highlight(jQuery插件)。

回答by Pixelomo

Just adding to Tony Miller's answer as this got me 90% towards what I was looking for but still didn't work. Adding .length > 0;to the end of his code got my script working.

只是添加托尼米勒的答案,因为这让我达到了我想要的 90%,但仍然没有用。添加.length > 0;到他的代码的末尾让我的脚本工作。

 $(function() {
    var foundin = $('*:contains("I am a simple string")').length > 0;
 });

回答by danatcofo

this function should work. basically does a recursive lookup till we get a distinct list of leaf nodes.

这个功能应该可以工作。基本上进行递归查找,直到我们得到一个不同的叶节点列表。

function distinctNodes(search, element) {
    var d, e, ef;
    e = [];
    ef = [];

    if (element) {
        d = $(":contains(\""+ search + "\"):not(script)", element);
    }
    else {
            d = $(":contains(\""+ search + "\"):not(script)");
    }

    if (d.length == 1) {
            e.push(d[0]);
    }
    else {
        d.each(function () {
            var i, r = distinctNodes(search, this);
            if (r.length === 0) {
                e.push(this);
            }
            else {
                for (i = 0; i < r.length; ++i) {
                    e.push(r[i]);
                }
            }
        });
    }
    $.each(e, function () {
        for (var i = 0; i < ef.length; ++i) {
            if (this === ef[i]) return;
        }
        ef.push(this);
    });
    return ef;
}