借助文本输入搜索过滤链接并隐藏不匹配的链接

Filter links with the help of text input search and hide non matching

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

Html 包含链接的容器,我想过滤并设置显示 none 如果不匹配:

<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>

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

JQuery 部分过滤我到目前为止写的链接:

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

使用 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 页面上的每个元素保留独特的 idid不应重复。
  • 上面给出的逻辑不使用 id 属性进行过滤。