【问题标题】:Filter links with the help of text input search and hide non matching借助文本输入搜索过滤链接并隐藏不匹配
【发布时间】:2017-11-21 12:47:46
【问题描述】:

我遇到了一个问题,我对 jquery 效果和功能不是很熟悉。 我想要一个简单的过滤器功能,您可以在其中过滤不同但相同的构建容器中的页面上的类别链接。 代码如下:

带有我要过滤的链接的 Html 容器,如果不匹配,则设置为不显示:

<div class="col-sm-3 py-4">
   <h4 class="text-white" id="hideOnFilter">Generatoren und Bilderupload</h4>
   <nav class="nav flex-column" id="filterholder">
      <a class="nav-link text-white catlink" href="#" title="Cat 1 description" id="filterelement">Cat 1</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 2 description" id="filterelement">Cat 2</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 3 description" id="filterelement">Cat 3</a>
      <a class="nav-link text-white catlink" href="#" title="Cat 4 description" id="filterelement">Cat 4</a>        
   </nav>
</div>

上面的这些容器在页面上放置了六次,但总是相同的类 ID 和结构。

JQuery 部分用于过滤我迄今为止编写的链接:

 $('.search').keyup(function(){
          var searchcatquery = $(this).val();
          //alert(searchcatquery); 
          //Filter and hide links which dont match to search input? 
          return false;
 });

【问题讨论】:

  • 要么不为元素保留任何id,要么为 HTML 页面上的每个元素保留独特的 id。 ids 不应重复。

标签: javascript jquery search filter show-hide


【解决方案1】:

使用jquery filter尝试这种方法

   $('.search').keyup(function(){
      var searchcatquery = $(this).val().toLowerCase(); //convert to lowercase     

      $(".catlink").show().filter(function(){
         return $(this).text().toLowerCase().indexOf( searchcatquery ) == -1 //filter all those who doesn't have searchcatquery as substring
      }).hide(); //hide filtered values

      return false;
    });

注意

  • 不要为元素保留任何id,或者为HTML 页面上的每个元素保留独特的id。 ids 不应重复。
  • 上面给出的逻辑不使用id 属性进行过滤。

【讨论】:

  • Rhx 对 ma 有很大帮助,但如何让它对大写字母不那么敏感。我的意思是,字母a是大写还是小写都不合理?
  • @PhilHedtmann 检查更新。您需要将要比较的两个值都转换为小写。
猜你喜欢
  • 1970-01-01
  • 2017-11-10
  • 2020-06-17
  • 2015-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-16
相关资源
最近更新 更多