html - 在不使用 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 插件,因为我不想要文本框输入键功能
提前致谢
解决方案
问题是因为您正在字符串中的任何位置寻找匹配项。解决此问题的简单方法是使用 将字符串分解为单词数组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>
推荐阅读
- mongodb - 使用 java 驱动程序在 MongoDb 中获取 ArrayOfObjects 值
- python - 查找两个时间段之间每周在项目上花费的小时数
- asp.net-core - 在不使用 Asp .net 核心包的情况下为 .net 核心控制台应用程序创建一个 websocket 服务器 olny
- c++ - 如何创建指向具有可变参数的函数的可调用函数指针?
- shell - 根据 shell 脚本中的字符串获取校验和
- sql - 使用雪花连接器在雪花中通过 python 执行 SQL 查询时,列名称为 0,1,2,3
- javascript - 按对象 ID 更新状态数组
- python-3.x - 为日志和结果动态生成目录
- python - 在 Azure 机器学习 Jupyter Notebook 中将 dict 保存为 json
- javascript - 在单独的组件中调用方法时,Angular Dom 不更新