我只是在谷歌上搜索一个可以用来在HTML表格中查找文本的脚本。
就像我创建一个包含许多列和行的学生姓名表。我有一个很好的脚本,显示我尝试搜索的任何内容,但它显示完整的行...
function searchSname() {
var input, filter, found, table, tr, td, i, j;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
}
}
if (found) {
tr[i].style.display = "";
found = false;
} else {
tr[i].style.display = "none";
}
}
}
&#13;
<input id='myInput' onkeyup='searchSname()' type='text'>
<table id='myTable'>
<tr>
<td>AB</td>
<td>BC</td>
</tr>
<tr>
<td>CD</td>
<td>DE</td>
</tr>
<tr>
<td>EF</td>
<td>GH</td>
</tr>
</table>
&#13;
但是知道我正在寻找一些更改来显示确切的文本,无论我搜索什么,而不是完整的行,就像它会显示我键入的文本来搜索和隐藏其他完全无法匹配的文本....
请告诉我是否可以仅显示我在表格中搜索的文字?就像我试图找到学生姓名&#34; AB&#34;然后它应该只显示AB而不是&#34; AB BC&#34;。
答案 0 :(得分:0)
这比制作它简单得多。
var cells = document.querySelectorAll("#myTable td");
var search = document.getElementById("myInput");
search.addEventListener("keyup", function(){
for(var i = 0; i < cells.length; ++i){
// This line checks for an exact match in a cell against what the
// user entered in the search box
//if(cells[i].textContent.toLowerCase() === search.value.toLowerCase()){
// This checks for cells that start with what the user has entered
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";
break;
} else {
cells[i].style.background = "white";
cells.forEach(function(element){
if(cells[i] !== element){
element.style.display = "table-cell";
}
});
}
}
});
&#13;
table, td { border:1px solid black; border-collapse: collapse;}
&#13;
<input id='myInput'>
<table id='myTable'>
<tr>
<td>AB</td>
<td>BC</td>
</tr>
<tr>
<td>CD</td>
<td>DE</td>
</tr>
<tr>
<td>EF</td>
<td>GH</td>
</tr>
</table>
&#13;