javascript - 调整表过滤器 Javascript
问题描述
我正在尝试调整一些当前允许用户在输入中输入文本的 javascript,然后它将隐藏所有不包含该文本的行。现在它只检查第一列,但我希望它检查第 1 列和第 2 列:
HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:20%;">Country</th>
<th style="width:20%;">Size</th>
</tr>
<tr>
<td>Joe Smith</td>
<td>Canada</td>
<td>Medium</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>Germany</td>
<td>Small</td>
</tr>
</table>
So in the simple example below, you could type either Jane or Germany to have that row show filter.
JAVASCRIPT:
<script>
function myFunction() {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
解决方案
尝试这个:
for (i = 0; i < tr.length; i++) {
var found = false;
for (j = 0; j < 3; j++){
td = tr[i].getElementsByTagName("td")[j];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
在列上创建一个内部循环,检查每一列。找到文本后,中断循环。循环后,检查找到的属性,设置路由显示。
推荐阅读
- time-complexity - 求 n0 和常数因子 c 的值,使得 f(n) = n log n 为 Ω(n)
- go - go mod 和 go get 的好习惯
- arrays - 当我尝试初始化 100 个元素的一维数组并使用指针填充它时,我遇到了分段错误(核心转储)
- routes - Vaadin (Flow) 21 从 20 升级 - 所有路线突然返回 404
- css - 具有 2 个类名的元素的 Scss 选择器
- verilog - 如何编写参数化延迟寄存器?
- ibm-cloud - 如何让 Watson Assistant 读取每个数字而不是整数
- algorithm - 通过删除不必要的点和堆叠形状来优化矢量图像
- android - attachToRecyclerView 不会从 RecyclerView 中删除以前的 ItemHelper
- javascript - React Hooks 中单选按钮输入的计算