【发布时间】:2019-07-04 04:56:02
【问题描述】:
我想创建一个带有过滤器的表格,该过滤器在显示搜索结果时突出显示已搜索的关键字。
我喜欢这个问题的答案:live highlight a word(s) with jQuery,但我不知道如何在我现有的代码中实现它。
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";
}
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search...">
<table id="myTable">
<tr>
<td>
<h1>Text</h1>
<p><span class="red">Text</span></p>
<p>Text</p>
</td>
<td><img src=".."></td>
</tr>
<td>
<h1>Text</h1>
<p><span class="red">Text</span></p>
<p>Text</p>
</td>
<td><img src=".."></td>
</table>
【问题讨论】:
-
所以您已经定义了一个目标并向我们展示了一些代码,但尚未确定该代码的具体问题或它产生的任何错误或代码具体做什么或不做什么以及在哪里你有具体的问题。还有助于在表格中提供足够的样本数据,使整个事情可以像minimal reproducible example 中那样运行
-
请注意,您可能很容易在网络上找到现成的突出显示脚本
-
看起来你只在第一个
中寻找你的单词匹配,如果你的单词恰好在该行的其他 td 标签中,它不会匹配那些。如果您想在其他 td 标记中查找单词,则必须添加一个嵌套循环以在这些标记中运行。
标签: javascript html html-table highlight