【问题标题】:Filtering HTML Table without using DataTable plugin在不使用 DataTable 插件的情况下过滤 HTML 表
【发布时间】:2021-05-27 07:52:43
【问题描述】:

我有一个 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”。

但我想在其中返回精确的“Crane”行。

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

提前致谢

【问题讨论】:

  • 您可以决定不显示搜索输入框,仅此而已:您无需重新发明轮子

标签: html jquery regex filter


【解决方案1】:

问题是因为您正在字符串中的任何位置寻找匹配项。简单的解决方法是使用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>

【讨论】:

  • 感谢您的回复@Rory McCrossan。您的代码行返回相反的结果,在这种情况下,我想通过排除“Crawler Crane”来过滤“Crane”。对这些代码行进行更多修改会更有帮助。
  • 在这种情况下,您是否正在寻找只能从字符串值的开头找到的搜索词?我看不出有任何其他方式可以让您从演示中的搜索词中获得预期的结果
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-10
  • 1970-01-01
  • 1970-01-01
  • 2019-05-18
  • 2012-06-19
  • 1970-01-01
  • 2020-10-31
相关资源
最近更新 更多