HTML表格搜索功能报错:Uncaught TypeError无法读取undefined的innerHTML
解决"Uncaught TypeError: Cannot read property 'innerHTML' of undefined"错误
这个错误的根源很清晰:你的循环把表头行也包含进去了!
问题分析
你通过table.getElementsByTagName("tr")获取了表格内所有的<tr>元素,其中第一行是表头行(包含的是<th>标签而非<td>)。当循环执行到这一行时,trs[index].getElementsByTagName("td")[0]找不到任何<td>元素,返回undefined,此时你尝试访问undefined的innerHTML属性,就会抛出这个类型错误。
另外还有一个容易忽略的小问题:你直接设置trs[index].display是无效的,要修改元素的显示状态,应该操作style.display属性。
解决方案
这里提供两种可靠的修复方式:
方式1:跳过表头行
因为表头是第一行(索引为0),我们可以从索引1开始循环,只遍历数据行:
function selectRow() { var input, filter, table, trs, td; input = document.getElementById("search"); filter = input.value.toUpperCase(); table = document.getElementById("dataRows"); trs = table.getElementsByTagName("tr"); // 从索引1开始,跳过表头行 for (let index = 1; index < trs.length; index++) { td = trs[index].getElementsByTagName("td")[0]; if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { trs[index].style.display = ""; } else { trs[index].style.display = "none"; } } }
方式2:先检查td元素是否存在
这种方式更灵活,即使表格后续添加了其他非数据行,也不会出错:
function selectRow() { var input, filter, table, trs, td; input = document.getElementById("search"); filter = input.value.toUpperCase(); table = document.getElementById("dataRows"); trs = table.getElementsByTagName("tr"); for (let index = 0; index < trs.length; index++) { td = trs[index].getElementsByTagName("td")[0]; // 先判断td是否存在,再执行后续逻辑 if (td) { if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { trs[index].style.display = ""; } else { trs[index].style.display = "none"; } } } }
验证效果
修改后,当你搜索"Area"这类属性时,就能正常匹配到对应的数据行,不会再抛出错误啦。
内容的提问来源于stack exchange,提问作者Cedi99
相关产品推荐
相关产品推荐

