我正在尝试创建一个 HTML 页面,其中包含一个包含一些文本的表格和一个用于在该表格中搜索文本的脚本。就像当我按下 a 时,它会突出显示所有带有 a 的文本。 该脚本成功地在表格中找到匹配的文本但是我在这个脚本中有一个问题,就像它只显示表格中的开始和最后一个匹配的单词而不是显示整个。附件是我的脚本和表格。
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function(){
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.background = "yellow";
cells[i].style.display = "table-cell";
continue;
cells[i].hide();
} else {
cells[i].style.background = "white";
cells.forEach(function(element){
if(cells[i] !== element){
element.style.display = "table-cell";
cells[i].show();
}
});
}
}
});
<input id='myInput' type='text'>
<table id='myTable'>
<tr>
<td>A</td>
<td>AA</td>
<td>AAA</td>
</tr>
<tr>
<td>B</td>
<td>BB</td>
<td>BBB</td>
</tr>
<tr>
<td>C</td>
<td>CC</td>
<td>CCC</td>
</tr>
</table>
我无法理解我做错了什么以及我的脚本中缺少什么。请看看它,让我知道我错过了什么或错了什么。 提前致谢
最佳答案
如果您运行您的代码片段,您会看到一个错误:
Uncaught TypeError: cells[i].show is not a function
这是因为 show()
是一种 jQuery 方法,在 DOMElement 上不可用。在这种情况下,您需要使用 .style.display = 'table-cell'
。
同样,hide()
也是一个 jQuery 方法,尽管当您在它之前调用 continue;
时没有显示错误,因此它永远不会被命中.该调用应该被删除(连同 continue
的冗余使用)或更改为 .style.display = 'none';
。
var cells = [].slice.call(document.querySelectorAll("#myTable td"));
var search = document.getElementById("myInput");
search.addEventListener("keyup", function() {
cells.forEach(function(cell) {
if (!search.value.trim()) {
cell.style.background = "white";
cell.style.display = 'table-cell';
} else if (cell.textContent.toLowerCase().indexOf(search.value.toLowerCase()) == 0) {
cell.style.background = 'yellow';
cell.style.display = "table-cell";
} else {
cell.style.background = "white";
cell.style.display = 'none';
}
});
});
<input id='myInput' type='text'>
<table id='myTable'>
<tr>
<td>A</td>
<td>AA</td>
<td>AAA</td>
</tr>
<tr>
<td>B</td>
<td>BB</td>
<td>BBB</td>
</tr>
<tr>
<td>C</td>
<td>CC</td>
<td>CCC</td>
</tr>
</table>
最后请注意,检查 indexOf() == 0
仅匹配字符串的开头。如果那是你的意图,那就太好了。如果您想检查字符串的任何部分是否匹配,请使用!= -1
关于javascript - 显示整个匹配单元格的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40914857/