首页 > 解决方案 > 在不使用 DataTable 插件的情况下过滤 HTML 表

问题描述

我有一个 HTML 表,我在 jQuery 中绑定了它的 tbody。

我正在尝试不使用 keyup 功能而是使用列表上的单击功能来过滤此表。在这里,我想过滤与我为过滤器函数传递的值完全匹配的表。

例如。

<table id="tableID">
 <thead>
   <tr>
   <th>Vehilce No </th>
   <th> Vehicle type </th>
   </tr>
 </thead>
 <tbody>
   <tr>
    <td> 1547 </td>
    <td> Cranes </td>
  </tr>
  <tr>
    <td> 5478 </td>
    <td> Crawler Crane </td>
  </tr>
  </tbody>
</table>

在这个例子中,如果我使用

var value = 'Crane'.toLowerCase();
                
$("#tableId tbody tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
}); 

此过滤器函数将返回这两行,因为这两行都包含值“Crane”。

但我想在其中返回精确的“起重机”行。

请注意:我不想使用 DataTable 插件,因为我不想要文本框输入键功能

提前致谢

标签: htmljqueryregexfilter

解决方案


问题是因为您正在字符串中的任何位置寻找匹配项。解决此问题的简单方法是使用 将字符串分解为单词数组split(),然后在该数组中的单词上找到完全匹配的单词。尝试这个:

let value = 'Crane'.toLowerCase();

$("#tableID tbody tr").hide().filter(function() {
  let containsWord = $(this).text().toLowerCase().split(/\b/).indexOf(value) != -1;
  $(this).toggle(containsWord);
}).show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableID">
  <thead>
    <tr>
      <th>Vehilce No </th>
      <th> Vehicle type </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td> 1547 </td>
      <td> Cranes </td>
    </tr>
    <tr>
      <td> 5478 </td>
      <td> Crawler Crane </td>
    </tr>
  </tbody>
</table>


推荐阅读