如何根据下拉菜单选中值筛选HTML表格第三列内容
问题修正说明
你的代码存在两处核心错误:
- 下拉选择器触发事件配置错误:
<select>元素选择选项时不会触发onkeyup事件,需替换为onchange事件才能在选择选项时执行筛选逻辑 - 表格单元格取值逻辑错误:
<td>属于普通文本容器,没有value属性,原代码td.value无法拿到单元格内容,需替换为td.textContent读取文本内容
修正后完整可运行代码
<!DOCTYPE html> <html> <script> function filterSector() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("sector"); filter = input.value; table = document.getElementById("portfolio"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[2]; if (td) { txtValue = td.textContent; if (txtValue.indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> <body> <select id="sector" onchange="filterSector()"> <option selected disabled hidden>Sectors</option> <option value="Industrials">Industrials</option> <option value="Information Technology">Information Technology</option> </select> <table id="portfolio"> <tr> <td>AAPL</td> <td>Apple</td> <td>Information Technology</td> </tr> <tr> <td>MMM</td> <td>3M</td> <td>Industrials</td> </tr> </body> </html>
可选优化(非必需)
如果需要实现不区分大小写的模糊筛选,可以把匹配逻辑修改为:
if (txtValue.toUpperCase().indexOf(filter.toUpperCase()) > -1)
这样哪怕后续选项和单元格内容大小写不一致也能正常匹配。
内容的提问来源于stack exchange,提问作者vauss
相关产品推荐
相关产品推荐

