我有来自w3schools的这个功能,它使搜索框接受输入,然后在表中搜索与输入值匹配的数据。 我得到了整个代码....除了部分,当它插入if和else语句在父if语句“if(td)”和代码甚至没有if语句运行时,为什么会发生?为什么我需要设置一个已经存在且不会改变的条件,因为总会有td!
<script>
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
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) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
答案 0 :(得分:0)
除了将
if
和else
语句插入父if
语句中时的部分&#34;if( td)
&#34;并且代码甚至在没有if语句的情况下运行,为什么会发生这种情况?
如果您打开浏览器的开发者工具,当您删除if
语句时,如果代码无法运行,因为您的HTML中包含的行不具备其中的任何细胞,如下:
<tr></tr>
if
声明正在防范这一点。
为什么我需要设置一个已经为真且不会改变的条件,因为总会有
td
!
好吧,如果删除if
语句后代码失败,那么 总是td
s tr
s
附注:代码可以更加简洁和有针对性,即使我们仅限于ES5中仅存在且不使用任何ES2015 +功能的内容:
function myFunction() {
var filter = document.getElementById("myInput").value.toUpperCase();
Array.protoype.forEach.call(
document.querySelectorAll("#myTable tr > td:first-child"),
function(td) {
td.parentNode.style.display =
td.innerHTML.toUpperCase().indexOf(filter) == -1 ? "none" : "";
}
);
}
答案 1 :(得分:0)
&#34; if (td)
&#34;测试非常重要,因为您可能有一个空行,没有td
,因此td
中的td = tr[i].getElementsByTagName("td")[0];
应该是未定义的,代码执行应该出错。
您可以使用浏览器的开发者控制台检查javascript错误(通常使用<f12>
键切换...