繁体   English   中英

如何用JQUERY搜索html中的文字?

[英]How to search text in html with JQUERY?

我试图用 jquery 在我的 html 代码中搜索文本,但没有运气,这是我的代码:

    $("body").on("searchByLikuy", function(e, msg) {
        msg = msg.replace(/'/g, "\'");
        found = $("*:contains('" + msg + "'):last");
        if(found.length > 0) {
            $('html, body').stop(true).animate({
                scrollTop: found.offset().top - 30
            }, 1000);
        }
    });

当html代码为:

<html>
<head>
</head>
<body>
<div class="test">
    abcde
</div>
</body>
</html>

我搜索味精“abcde”它的工作正常并在“找到”变量中返回我需要的东西。 但是当 html 代码是:

<html>
<head>
</head>
<body>
<div class="test">
    <span>a</span>
    <span>b</span>
    <span>c</span>
    <span>d</span>
    <span>e</span>
</div>
</body>
</html>

它不返回任何东西。 我可以做什么来搜索?

发件人

您可以简单地尝试:

if( $("body").text().includes(msg) ) { ...

或者使用正则表达式:

if( new RegExp(msg, "i").test( $("body").text() )) { ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM