【发布时间】:2018-09-20 07:18:07
【问题描述】:
if(td) 条件在这里做什么?编写此代码是为了在表中搜索一行。
var input 是搜索框,var table 是表格。
function myFunction() {
// this function filters the table using search box
var input, filter, table, tr, td, i;
input = document.getElementById("myInput"); // the search box
filter = input.value.toUpperCase();
table = document.getElementById("myTable"); // the table
tr = table.getElementsByTagName("tr"); // the row of table
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) { // why do we need this condition here?
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
【问题讨论】:
-
如果一行没有
<td>元素,那么变量将为undefined。
标签: javascript html if-statement filtering