这是我在 Stackoverflow 上发表的第一篇文章。很高兴来到这里! 我在一家从事 HTML、CSS、Jquery、Ajax、SQL 工作的公司实习已经进入第 8 周。
刚开始的时候我还是个新手,但我正在慢慢掌握它。
我遇到了一些我不知道如何解决的问题。
我的页面显示来自 SQL 数据库的表。它还有一个带有类别的标题。
我制作了搜索栏,以便我可以输入 ID,然后它会实时显示结果。我真正想要的是能够搜索所有内容。所以 Id、client、certname、supplier_id、partner_nr 等。
有人知道我需要做什么吗?
这是我与这部分相关的代码:
**HTML:
<form class="form-inline my-2 my-lg-0" id="searchTable">
<input class="form-control mr-sm-2" type="search" name="searchInput" placeholder="Search" aria-label="Search">
</form>
Main.js
$("input[name=searchInput]").on('change keypress paste focus textInput input',function(){
// Declare variables
var input, filter, table, tr, td, i, x;
input = $(this).val();
filter = input.toUpperCase();
table = document.getElementById("cfgAccounts");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (x = 0; x < td.length; x++) {
td = tr[i].getElementsByTagName("td")[x];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
});
最佳答案
如果您想搜索整行,只需将代码中的 for 循环更改为:
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i];
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
无需遍历每个 td 单元格。
关于javascript - 使用 Javascript 搜索表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49688598/