ITeye博客

查找文本并高亮

winzenghua · 2011-02-21 16:48 · Markdown

让我们来看一下如何使用 jQuery 去查找或搜索一段文本并高亮它。

我是 jQuery 的忠实粉丝,喜欢它简介的语法。接下来让我演示一个示例:仅使用一行 jQuery 代码便可把搜索字段进行高亮。


<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <title>Search Text in jQuery from DevCurry.com</title>
        <style type="text/css">        div { height: 50px; width: 150px; border: 1px solid blue; }        </style>
        <script type="text/javascript"    src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.min.js"></script>
        <script type="text/javascript">    
            $(function () {        
                $("#btnSearch").click(function () {
                   $("div:contains('simple')").css("border", "4px solid blue");        
                });
           });
        </script>
    </head>
    <body> 
        <div id="divOne">DivOne. This is a simple looking DIV</div><br />  
        <div id="divTwo">DivTwo. This is another simple looking DIV</div><br />  
        <div id="divThree">DivThree. This is just a DIV</div><br />
       <div id="divFour">DivFour. This is again a DIV</div><br />  
        <div id="divFive">DivFive. Yet another simple looking DIV</div><br />
        <input id="btnSearch" type="button" value="Search" />
    </body>
</html>

这里我们使用 jQuery 中的 contains 选择器来在被锁定的元素及这些元素的后代中进行特定字符的查找。

如果 div 标签内包含 “simple” 文本,那么该 div 标签将会被高亮:宽度变为 4px,这些只需要一行代码。

提示: contains() 是大小写敏感的

jquery search text

显示结果

jquery search text

改进版本:

$("div:contains('simple')"
).html($("div:contains('simple')"
).html().replace(/simple/g, "simple
"));        

改进自:http://www.phphosts.org/2011/02/jquery-find-text-and-highlight-elements/

本文是使用 B3log Solo 从 Vanessa 进行同步发布的

原文地址:http://vanessa.b3log.org/jQuery-contains

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。