我已经关注了这个 link关于如何创建/过滤搜索表。但我想过滤搜索我自己表中的每一列。 目前,它只搜索 First Name 列。我该怎么做?
这是代码:
我的HTML:
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
<tr class="header">
<th> First Name </th>
<th> Last Name </th>
<th> Age </th>
<th> Language </th>
</tr>
<tr>
<td>John</td>
<td>Kole</td>
<td>18</td>
<td>English</td>
</tr>
<tr>
<td>Pearl</td>
<td>Shine</td>
<td>50</td>
<td>Hindi</td>
</tr>
<tr>
<td>Jacob</td>
<td>Pool</td>
<td>22</td>
<td>Arabic</td>
</tr>
<tr>
<td>David</td>
<td>Struff</td>
<td>30</td>
<td>German</td>
</tr>
</table>
<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>
如何筛选所有列以进行搜索?目前,它仅搜索名字列。
最佳答案
检查表格行的每个节点而不是只检查tr[i].getElementsByTagName("td")[0]
.第零个节点对应于名字字段,这就是搜索结果仅限于名字字段的原因。改为搜索所有节点。
离开tr
类名为 header
的节点同时隐藏该行。
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];
alltags = tr[i].getElementsByTagName("td");
isFound = false;
for(j=0; j< alltags.length; j++) {
td = alltags[j];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
j = alltags.length;
isFound = true;
}
}
}
if(!isFound && tr[i].className !== "header") {
tr[i].style.display = "none";
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
<tr class="header">
<th> First Name </th>
<th> Last Name </th>
<th> Age </th>
<th> Language </th>
</tr>
<tr>
<td>John</td>
<td>Kole</td>
<td>18</td>
<td>English</td>
</tr>
<tr>
<td>Pearl</td>
<td>Shine</td>
<td>50</td>
<td>Hindi</td>
</tr>
<tr>
<td>Jacob</td>
<td>Pool</td>
<td>22</td>
<td>Arabic</td>
</tr>
<tr>
<td>David</td>
<td>Struff</td>
<td>30</td>
<td>German</td>
</tr>
</table>
希望这就是您要找的。p>
关于javascript - 如何过滤/搜索 HTML 表格中的列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59560207/