如何用JavaScript获取多个tag索引,实现表格全列搜索?
实现表格多列搜索的解决方案
你现在的代码只检查了每行的第一个<td>元素,所以只能搜索第一列。要实现整表多列搜索,需要遍历每行的所有单元格,只要有任意一列匹配关键词,就保留该行。
修改后的JavaScript代码如下:
function myFunction() { var input, filter, table, tr, tds, i, j, txtValue, found; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { // 获取当前行的所有td元素 tds = tr[i].getElementsByTagName("td"); found = false; // 标记是否找到匹配内容 // 遍历当前行的每个td for (j = 0; j < tds.length; j++) { txtValue = tds[j].textContent || tds[j].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { found = true; break; // 找到匹配就停止遍历当前行的td } } // 根据found状态设置行的显示 tr[i].style.display = found ? "" : "none"; } }
关键改动说明:
- 新增
tds变量存储当前行的所有<td>元素,不再只取单个索引的td - 添加
found布尔变量,用来标记当前行是否存在匹配的内容 - 嵌套循环遍历当前行的每个单元格,只要有一个单元格匹配关键词,就将
found设为true并跳出循环 - 最后根据
found的值决定显示或隐藏当前行
完整的可运行代码如下:
HTML
<h2>My Customers</h2> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names or countries.." title="Type in a keyword"> <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> <tr> <td>Laughing Bacchus Winecellars</td> <td>Canada</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Italy</td> </tr> <tr> <td>North/South</td> <td>UK</td> </tr> <tr> <td>Paris specialites</td> <td>France</td> </tr> </table>
CSS
* { box-sizing: border-box; } #myInput { background-image: url('/css/searchicon.png'); background-position: 10px 10px; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 12px 20px 12px 40px; border: 1px solid #ddd; margin-bottom: 12px; } #myTable { border-collapse: collapse; width: 100%; border: 1px solid #ddd; font-size: 18px; } #myTable th, #myTable td { text-align: left; padding: 12px; } #myTable tr { border-bottom: 1px solid #ddd; } #myTable tr.header, #myTable tr:hover { background-color: #f1f1f1; }
JavaScript
function myFunction() { var input, filter, table, tr, tds, i, j, txtValue, found; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { tds = tr[i].getElementsByTagName("td"); found = false; for (j = 0; j < tds.length; j++) { txtValue = tds[j].textContent || tds[j].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { found = true; break; } } tr[i].style.display = found ? "" : "none"; } }
内容的提问来源于stack exchange,提问作者Dannie
相关产品推荐
相关产品推荐

