首页 > 解决方案 > 用JS隐藏标题过滤HTML表格

问题描述

我目前有一个 HTML 表格的过滤器,示例如下。这也过滤了标题。

  <div class="col-md-3 col-md-offset-3" style="padding-bottom: 20px;">
  <input type="text" class="form-control" id="Search" onkeyup="SearchBar()" placeholder="Search">
</div>

<table id="MainTable" class="table table-condensed table-hover">
    <thead>
      <th width="2%" style="text-align: center;"></th>
      <th width="50%">Display Name</th>
      <th width="20%">Dashboard</th>
    </thead>
    <tbody>
     <tr class="">
      <td style="text-align: center;">a</td>
      <td>DashboardTest</td>
      <td>b</td>
     </tr>
    </tbody>
</table>


function SearchBar() {
 var $rows = $('#MainTable tr');
    $('#Search').keyup(function() {
        var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

        $rows.show().filter(function() {
            var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
            return !~text.indexOf(val);
        }).hide();
    });
}

有没有办法使用这个JS不包含thead?

标签: javascripthtml

解决方案


是的。您只能在 TBODY 中搜索。给 TBODY 一个 id="MyBody" 将此行更改为: var $rows = $('#MyBody tr'); 它不会再在 thead 中搜索了。


推荐阅读