如何修改JS代码实现表格姓名与国家列的文本搜索?
实现多列表格过滤的修改方案
修改后的完整代码
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names or countries.."> <table id="myTable"> <tr class="header"> <th style="width:60%;">Name</th> <th style="width:40%;">Country</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Germany</td> </tr> <tr> <td>Berglunds snabbkop</td> <td>Sweden</td> </tr> <tr> <td>Island Trading</td> <td>UK</td> </tr> <tr> <td>Koniglich Essen</td> <td>Germany</td> </tr> </table> <script> function myFunction() { // Declare variables var input, filter, table, tr, tds, i, j, txtValue, matchFound; 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++) { tds = tr[i].getElementsByTagName("td"); matchFound = false; // 遍历当前行的所有单元格 for (j = 0; j < tds.length; j++) { txtValue = tds[j].textContent || tds[j].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { matchFound = true; break; // 找到匹配就跳出单元格循环 } } // 根据匹配结果设置行的显示状态 if (matchFound) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } </script>
关键修改点说明
- 替换单列获取为多列遍历:移除原代码中仅获取第一个单元格的
td = tr[i].getElementsByTagName('td')[0];,改为获取当前行的所有单元格集合tds = tr[i].getElementsByTagName("td");。 - 新增匹配状态标记:定义
matchFound变量,初始设为false,用于记录当前行是否有任意单元格匹配搜索关键词。 - 遍历所有单元格检查匹配:新增内层循环遍历当前行的每个单元格,只要有一个单元格的文本包含搜索关键词,就将
matchFound设为true并跳出内层循环,避免不必要的遍历。 - 根据匹配结果控制行显示:不再基于单个单元格判断,而是根据
matchFound的值决定当前行是否显示。
可选简化方案(合并整行文本)
如果不需要精确到单个单元格检查,也可以直接获取整行的所有文本内容进行匹配,代码更简洁:
function myFunction() { var input, filter, table, tr, i, rowText; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // 从i=1开始跳过表头行 for (i = 1; i < tr.length; i++) { rowText = tr[i].textContent || tr[i].innerText; if (rowText.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } }
这个方案会把当前行的所有文本合并后检查,适合简单场景,代码中通过i=1开始循环跳过了表头行。
内容的提问来源于stack exchange,提问作者salp
相关产品推荐
相关产品推荐

