使用 javascript 过滤表格
2021-08-04
1323
我正在尝试使用 JavaScript 函数过滤表格,但我不确定问题是什么...单击过滤器链接时,什么都没有发生,但它应该过滤第二列(“平台”列)并且仅显示包含“TEST”的行。
我正尝试在这里调试它:
https://jsfiddle.net/7vh5wmsx/
function filterTable(input) {
var filter = input.value.toUpperCase();
var table = document.getElementById("myTable");
var tr = table.getElementsByTagName("tr");
var tds = tr.getElementsByTagName('td');
for (var i = 0; i < tr.length; i++) {
if (tds[1].textContent.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
2个回答
使用此代码
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
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")[0];
if (td) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
2021-08-04
这将执行您所描述的操作,同时忽略第一行(即标题)
const searchbar = document.getElementById("myInput");
// ignore the first row which is the header
const rows = Array.from(document.querySelectorAll('#myTable tr')).slice(1);
function filterTable() {
const substr = searchbar.value.toLowerCase();
rows.forEach((row) => {
// cells[1] is the second column
row.style.display = row.cells[1].textContent.toLowerCase().includes(substr) ? "" : "none";
})
}
Oenomaus
2024-07-09