JavaScript筛选HTML表格时子表格消失的问题排查及代码修改咨询
JavaScript筛选HTML表格时子表格消失的问题排查及代码修改咨询
嗨,我来帮你分析并解决这个问题~
问题根源
你遇到的子表格消失问题,核心原因是代码误获取了表格中所有层级的<tr>元素:
原来的table.getElementsByTagName("tr")方法会遍历整个表格DOM树,把主表格的行和子表格里的行全部捞出来。当循环到子表格的<tr>时,它的第一个<td>内容大概率不匹配搜索关键词,就会被设置为style.display = "none",子表格自然就跟着消失了。
解决方案
我们需要精准针对主表格的直接子行进行筛选操作,而不是所有<tr>。可以用querySelectorAll配合子选择器>来只获取主表格的直接子行。
修改后的完整代码
JavaScript部分:
function filter_country_table_country_name_or_code() { // Declare variables var input, filter, table, tr, td, i, txtValue; input = document.getElementById("country_name_or_code_input"); filter = input.value.toUpperCase(); table = document.getElementById("country_table"); // 关键修改:只获取主表格的直接子tr元素 tr = table.querySelectorAll(" > tr"); // Loop through all main 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"; } } } } function clear_country_table_country_name_or_code_field() { document.getElementById('country_name_or_code_input').value = ""; filter_country_table_country_name_or_code() }
HTML部分(修正了不符合规范的文本放置,确保逻辑正常运行):
<table id="country_table"> <tr> <td>Main Table Content Row 1</td> <table> <tr> <td> Sub-Table Content Row 1 </td> </tr> </table> </tr> <tr> <td>Main Table Content Row 2</td> <table> <tr> <td> Sub-Table Content Row 2 </td> </tr> </table> </tr> </table>
效果说明
修改后,代码只会处理主表格的直接子行:
- 当主行匹配搜索关键词时,主行正常显示,它包含的子表格也会跟着正常展示;
- 当主行不匹配时,整个主行(包括子表格)会被隐藏,不会单独隐藏子表格的行,完美解决子表格消失的问题。
备注:内容来源于stack exchange,提问作者Don
相关产品推荐
相关产品推荐

