如何在表格中显示多个单元格搜索
问题描述:
我想知道是否有用于显示多个元素的搜索栏的方法。现在,如果我在“321”“123”“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
这是一个arrayish对象。这没有forEach
函数。
不过我们可以从数组对象借:
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>
答
下面的代码是不够的,如果你想显示其细胞已包含搜索;你也可以测试的jsfiddle https://jsfiddle.net/bzcdomjs/
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function() {
for (var i = 0; i < cells.length; ++i) {
cells[i].style.display = "table-cell";
if (search.value.length > 0 && search.value != '') {
if(cells[i].textContent.toLowerCase().indexOf(search.value.toLowerCase()) === -1) {
cells[i].style.display = "none";
}
}
});
这是伟大的,将使用它,但它有可能使它所以搜索的方式工作,如果我输入“1”,将只显示结果从1开始,而不是包含1的那个? – SchwiftyTV
刚把-1改为0,这样做就是这样! – Mouser
这对我的项目来说非常有效,但最后一件事情是。如果搜索“abcde”,结果就会显示出来,没问题,但是当你退回到“abc”时,它仍然只显示“abcde”。有没有可能用我现有的代码解决这个问题? – SchwiftyTV