javascript - 如何通过任何匹配的代码/名称而不是每个可用字段来过滤表
问题描述
我正在尝试执行以下操作:我有一个填充了数据库数据的表。除此之外,我还有一个输入,您可以在其中写一些东西,还有一个可以过滤的按钮,只显示具有该字符串的行。这正在工作!
问题是,输入应该只允许您过滤foo.name/foo.code
(我的实体的两个属性)。
我正在添加我拥有的代码,以防有人可以指导我,我已经尝试了几件事,但这是我第一次使用 JQuery,而我有严格的故事交付时间。感谢大家!
<tbody>
<c:forEach var="foo" items="${foo}">
<tr id = "fooInformation" class="mtrow">
<th id="fooName" scope="row">${foo.name}</th>
<td id="fooCode" class="left-align-text">${foo.code}</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</c:forEach>
</tbody>
$("#search").click(function () { -> button id
var value = $("#fooRegionSearch").val(); -> value of the input
var rows = $("#fooRegionTable").find("tr"); -> table id
rows.hide();
rows.filter(":contains('" + value + "')").show();
});
解决方案
首先,您的 HTML 无效 - HTML 中不能有具有重复 ID 的元素。使用类而不是 ID。
然后,您需要确定哪些 TR 通过了测试。.filter
可以接受一个回调,所以给它一个函数,给定一个 TR,选择它的fooName
和fooCode
包含value
使用:contains
jQuery 选择器的子元素:
$("#search").click(function() {
var value = $("#fooRegionSearch").val();
var rows = $("#fooRegionTable").find("tr");
rows.hide();
rows.filter(
(_, row) => $(row).find('.fooName, .fooCode').filter(`:contains('${value}')`).length
).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fooRegionTable">
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name1</th>
<td class="fooCode" class="left-align-text">code1</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
<tr id="fooInformation" class="mtrow">
<th class="fooName" scope="row">name2</th>
<td class="fooCode" class="left-align-text">code2</td>
<td class="left-align-text">${foo.country}</td>
<td class="left-align-text">${foo.region}</td>
<td class="left-align-text">${foo.subregion}</td>
</tr>
</table>
<button id="search">click</button><input id="fooRegionSearch" />
推荐阅读
- python - 验证 DOM 中不存在的元素
- html - 插入其他内容时,问题页脚有阴影
- typescript - 将 Aurelia TS 变量中的 HTML 输出到视图中
- lua - 为什么解释器抱怨名为“math”的库不存在?
- scala - Scala 继承类型不满足父类型要求
- python - 不要在特定日期运行 Autosys 作业
- python - 从两个字符串列中提取 YYYY 年份并将其放入新列中,保留 NaN 值
- node.js - 如何在 Google Chat API 中添加带有复选框的选项
- android - 在android中将布局转换为图像是什么意思
- javascript - 每次添加产品时增加 totalAmount