我想知道是否有一种方法可以让我用来显示多个元素的搜索栏。现在,如果我在带有“321”“1234”“123”“12345”的池中搜索“123”,唯一显示的值将是第一个:“1234”。我希望显示与我的搜索匹配的所有值,因此这将是正确的搜索结果:“1234”“123”“12345”。
任何答案都值得赞赏。
这是我当前的代码:
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function() {
if (search.value.length > 0 && search.value != '') {
for (var i = 0; i < cells.length; ++i) {
if (cells[i].textContent.toLowerCase().indexOf(search.value.toLowerCase()) === 0) {
cells.forEach(function(element) {
element.style.display = "none";
});
cells[i].style.display = "table-cell";
break;
} else {
cells.forEach(function(element) {
if (cells[i] !== element) {
element.style.display = "table-cell";
}
});
}
}
} else {
cells.forEach(function(element) {
if (cells[i] !== element) {
element.style.display = "table-cell";
}
});
}
});
<input id="myInput">
<table id="myTable">
<tr>
<td>321</td>
<td>123</td>
</tr>
<tr>
<td>1234</td>
<td>abc</td>
</tr>
<tr>
<td>12345</td>
<td>abcde</td>
</tr>
</table>
最佳答案
您的cells
选择器返回一个nodelist
,这是一个数组对象。它没有 forEach
函数。
但是我们可以借用 Array 对象:
Array.prototype.forEach
我为解决另一个问题所做的就是创建一个 indexArray
作为查找数组。跟踪包含搜索字符串的索引。然后,当我们循环所有单元格时,我们可以转动那些没有出现在查找数组中的单元格
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function() {
var indexArray = []; //look up array
for (var i = 0; i < cells.length; ++i) {
//restore the cells:
cells[i].style.display = "table-cell";
//if search value is found the value will be 0 if it starts a the beginning
if (cells[i].textContent.toLowerCase().indexOf(search.value.toLowerCase()) === 0) {
indexArray.push(i); //push index into lookup
}
}
//loop over all cells
Array.prototype.forEach.call(cells, function(element, index) {
if (indexArray.indexOf(index) === -1) //if index is not present in look up, set display to none
element.style.display = "none";
});
});
<input id="myInput">
<table id="myTable">
<tr>
<td>321</td>
<td>123</td>
</tr>
<tr>
<td>1234</td>
<td>abc</td>
</tr>
<tr>
<td>12345</td>
<td>abcde</td>
</tr>
</table>
关于javascript - 如何在表格搜索中显示多个单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46868213/