【问题标题】:adding a background color to search term results为搜索词结果添加背景颜色
【发布时间】:2010-04-30 05:19:25
【问题描述】:

当用户在页面(基本上是一个大表)上输入搜索词时,我正在尝试为用户提交的搜索结果添加背景颜色。这是基于文本的搜索。我正在使用 jquery 在 TR 中显示/隐藏没有搜索词作为文本的表行,但理想情况下,我希望采取额外的步骤来获取搜索词(输入的值),并匹配任何其余(显示)行中的这些文本术语,并为单词添加黄色背景。我知道我的语法目前是错误的,只是不确定什么是正确的:)希望这很清楚......非常感谢任何帮助!

$("#searchsubmit").click(function () {
	var searchexp = document.getElementById('searchbox').value;
	$("table tr").hide();
	$("table tr.header").show();
	$('tr:contains('+ searchexp +')').show();
	$(searchexp).css('background-color','yellow');
	});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="searchform" method="get" action="#">
  <input type="text" id="searchbox" />
  <input type="submit" value="Search" id="searchsubmit" />
</form>

【问题讨论】:

    标签: jquery jquery-ui


    【解决方案1】:

    您想要隐藏其内容中有 0 个匹配项的 &lt;tr&gt;,并且您还希望突出显示匹配的 &lt;tr&gt;s 中的匹配文本。

    为此,您需要使用正则表达式 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)

    您接受输入,然后使用 RegExp 匹配您要查找的字符串的所有实例。您遍历每个表&lt;tr&gt;,在其中您遍历所有&lt;td&gt;,获取它们的文本,并将匹配的字符串替换为黄色的&lt;span&gt;。您还将变量foundSomeMatch 设置为true,因此在完成对&lt;tr&gt; 的迭代后,如果有任何匹配项,您可以.show() 您当前所在的&lt;tr&gt;。

    您可以在下面的代码 sn-p 中尝试一下,尝试搜索 test、test1 或 new entry 以查看过滤器的工作原理。

    $(document).ready(function(){
       $("#searchsubmit").click(function () {
    	var searchexp = $("#searchbox").val();
    	$("table").find("tr").hide();
            var matchSearched = new RegExp(searchexp,"ig");
    
            $("table").find("tr").each(function(){
               var foundSomeMatch = false;
               $(this).find("td").each(function(){
                   let textInside = $(this).text();
                   textInside = textInside.replace(matchSearched, function myFunction(x){
                       foundSomeMatch = true;
                       return '<span style="background-color: yellow;">'+x+'</span>';
                   });
                   $(this).html(textInside);
                  if(foundSomeMatch){
                      $(this).closest("tr").show();
                  }
               });
            });
       });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <form id="searchform" method="get" action="#">
      <input type="text" id="searchbox" />
      <input type="submit" value="Search" id="searchsubmit" />
    </form>
    
    
    <table>
       <tbody>
          <tr><td>test1</td></tr>
          <tr><td>test2</td></tr>
          <tr><td>new entry</td><tr>
       </tbody>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-23
      • 2013-10-10
      • 2018-04-19
      • 2016-07-24
      • 1970-01-01
      • 2021-01-15
      • 2013-05-23
      • 1970-01-01
      相关资源
      最近更新 更多