我之所以使用a bit of code from w3schools是因为它正是我要寻找的东西,但是我需要使它适用于多个表列。我知道问题出在哪里,input = document.getElementById("search");
行将找到第一个ID并使用它。我需要一种方法,使其独特,而不必为每个列创建脚本。否则它可以正常工作,并且可以在我的表中扩展。这是我正在使用的代码:
的HTML
<tr>
<th><input type="text" id="search" onkeyup="searchFunction(0)"></th>
<th><input type="text" id="search" onkeyup="searchFunction(1)"></th>
<th><input type="text" id="search" onkeyup="searchFunction(2)"></th>
<th><input type="text" id="search" onkeyup="searchFunction(3)"></th>
</tr>
JS
function searchFunction(n) {
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("search");
filter = input.value.toUpperCase();
table = document.getElementById("table");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[n];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
搜索其他答案使我尝试使用
input = n.querySelector('.search')
之类的东西,使用searchFunction(this),并将所有HTML ID更改为类,但是我仍然得到TypeError:输入为空
我不知道我是否在正确的轨道上
最佳答案
我建议您在页面上使用唯一的id属性。您可以将id
更改为class
es,并使用document.querySelectorAll('.search')
获取输入列表。