如何在jquery中突出显示匹配项的文本?

时间:2012-11-13 22:56:29

标签: javascript jquery

我有项目列表和搜索框。如果在搜索框中输入搜索词,则匹配的文本应在列表中以粗体字母显示,而不考虑大小写(不区分大小写)。 我已达到某种程度,但后来我不知道该怎么做,因为我是jquery的新手。

<html>
<head>
    <script type="text/javascript" 
          src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
          $(".SearchElement").keyup(function(){
            keyword = $(".SearchElement").val();
            if(keyword.length>=3){
                 var content = $(".wrapperbox ul li").text();
                 test = content.match(/keyword/gi)
                 if(test){
                     //alert(test);
                 }
            }
          });
        });
    </script>
</head>
<body>
    <form action="">
        <label>SearchTerm:</label> <input type="text" 
        name="SearchBox" value="" class="SearchElement" />
    </form>
    <div class="wrapperbox">
        <ul>
            <li>TestString</li>
            <li>testString</li>
            <li>Kanigiri</li>
            <li>KANIGIRI</li>
        </ul>
    </div>
</body>
</html>

我怎么能这样做,任何帮助都会受到极大的关注。谢谢

1 个答案:

答案 0 :(得分:1)

<html>
<head>
    <script type="text/javascript" 
          src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
       $(document).ready(function(){
          $("#SearchElement").keyup(function(){
            keyword = $("#SearchElement").val();
            if(keyword.length>=3){
                 $(".wrapperbox ul li").each(function(index) {
                      var content =  = $(this).text());
                      test = content.match(/keyword/gi);
                      if (test){
                           $(this).replaceWith( "<li><b>" + $(this).text() + "</b></li>" );
                      }                      
                 });

            }
          });
        });
    </script>
</head>
<body>
    <form action="">
        <label>SearchTerm:</label> <input type="text" 
        name="SearchBox" id="SearchBox" value="" class="SearchElement" />
    </form>
    <div class="wrapperbox">
        <ul>
            <li>TestString</li>
            <li>testString</li>
            <li>Kanigiri</li>
            <li>KANIGIRI</li>
        </ul>
    </div>
</body>
</html>
  1. 使用ID引用表单输入
  2. 使用each()循环
  3. 基本上在这个循环中找到并找到替换(我做了一个弱版本 - 未经测试,并根据你的代码,来帮助你)但希望你能看到我要去哪里