2012-11-13 21 views
0

我有项目列表和一个搜索框。如果搜索词输入到搜索框中,匹配的文本应该在列表中以粗体字显示,而不考虑大小写(不区分大小写)。 我做了一些水平,但后来我不知道该怎么做,因为我是新来的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> 

我该怎么做,任何帮助将大大appriciated。谢谢

+0

看看我的回答[此问题](http://stackoverflow.com/questions/12505602/slow-highlighting -in-火狐/ 12505656#12505656)。 – elclanrs

+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. 使用每个()循环
  3. 基本上捣鼓约,发现环路内更换(我做了一个弱版本 - 未经测试,并根据你的代码,以帮助你),但希望你能看到我要去哪里
+0

非常感谢您的回复,我只需要突出显示匹配的文字。我怎样才能做到这一点 ? – user964147

+0

查找/替换..在每个循环尝试'$(this).text = $(this).text.replace(关键字,“”+关键字+“”);' – conners

+0

它是这样的..你可能需要在'.html()'而不是'.text()'内部进行替换 – conners