首页 > 解决方案 > 基于搜索字符串的jQuery隐藏列

问题描述

我想根据搜索到的文本(td)隐藏表格列。像这样的东西

jQuery("#searchTableInput2").on("keyup", function() {
    var value = jQuery(this).val();
   jQuery("#searchTable2 tr td:not(:contains('"+ value +"')")).('hide columns');
});

互联网上没有这样的例子。任何帮助将不胜感激。

标签: jquery

解决方案


尝试这个。

$( document ).ready(function() {
  $("#searchTableInput2").on("keyup", function() {
    let searchKey = $(this).val().toLowerCase();
    $('#searchTable2 tr td,#searchTable2 tr th').show();
    if(searchKey == '') return;
    var colCount = $("#searchTable2 tr th").length;
    for (i = 1; i <= colCount; i++) {
      let keyExists = false;
      $('#searchTable2 tr td:nth-child('+i+')').each( function(){
        if($(this).text().toLowerCase().includes(searchKey)) {
          keyExists = true;
          return;
        }      
      });
      if(!keyExists) {
        $('#searchTable2 tr td:nth-child('+i+'), #searchTable2 tr th:nth-child('+i+')').hide();
      }
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="searchTableInput2" value=""/>

<table id="searchTable2" style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>
</table>


推荐阅读