如何修改代码实现搜索Bootstrap表格第二列而非默认第一列内容
解决方案
你只需要修改JS代码中获取表格单元格的索引即可,HTML的占位提示建议同步修改适配搜索逻辑:
核心修改点
- JS代码里
tr[i].getElementsByTagName("td")[0]的索引0对应第一列Name字段,改为索引1就会匹配第二列Country字段 - 输入框原有placeholder是「Search for names..」,建议改为「搜索国家名称..」更符合当前功能
修改后完整代码
function myFunction() { // 声明变量 var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("myTable"); tr = table.getElementsByTagName("tr"); // 遍历所有表格行,隐藏不符合搜索条件的行 for (i = 0; i < tr.length; i++) { // 这里把原来的[0]改成[1],获取第二列单元格 td = tr[i].getElementsByTagName("td")[1]; if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } }
<!-- 把placeholder修改为对应国家搜索的提示 --> <input type="text" id="myInput" onkeyup="myFunction()" placeholder="搜索国家名称.."> <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> </table>
内容的提问来源于stack exchange,提问作者Pouya Vaghefi
相关产品推荐
相关产品推荐

