如何使用多个下拉菜单实现HTML表格多条件联动筛选
实现多条件叠加筛选的修改方案
核心调整思路:放弃原有的两个独立筛选函数,改为触发任意筛选时同时校验所有维度的筛选条件,只要行数据不满足任意一个已选条件就隐藏,从而实现筛选效果叠加。
具体修改点:
- 将两个下拉选择框的
onchange事件都绑定到同一个统一筛选函数 - 统一筛选函数中同时读取两个下拉框的选中值,逐行匹配所有筛选规则
- 对
ALL选项(空值)做兼容,空值代表该维度不做筛选限制
完整可运行代码:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { 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; } #mylist { 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; } </style> </head> <body> <h2>菜品筛选</h2> <select id="mylist" onchange="filterTable()" class='form-control'> <option value="">全部</option> <option value="fish">鱼</option> <option value="chicken">鸡肉</option> </select> <h2>接收人筛选</h2> <select id="mylist1" onchange="filterTable()" class='form-control'> <option value="">全部</option> <option value="receiver1">接收人1</option> <option value="receiver2">接收人2</option> <option value="receiver3">接收人3</option> </select> <table id="myTable"> <tr class="header"> <th style="width:60%;">接收人</th> <th style="width:40%;">菜品</th> </tr> <tr> <td>receiver1</td> <td>fish</td> </tr> <tr> <td>receiver1</td> <td>fish</td> </tr> <tr> <td>receiver2</td> <td>chicken</td> </tr> <tr> <td>receiver2</td> <td>chicken</td> </tr> <tr> <td>receiver3</td> <td>fish</td> </tr> <tr> <td>receiver3</td> <td>chicken</td> </tr> </table> <script> function filterTable() { // 获取两个筛选条件 const dishFilter = document.getElementById("mylist").value.toUpperCase(); const receiverFilter = document.getElementById("mylist1").value.toUpperCase(); const table = document.getElementById("myTable"); const tr = table.getElementsByTagName("tr"); // 遍历所有数据行 for (let i = 0; i < tr.length; i++) { // 跳过表头行 if (tr[i].classList.contains('header')) continue; const tdReceiver = tr[i].getElementsByTagName("td")[0]; const tdDish = tr[i].getElementsByTagName("td")[1]; if (tdReceiver && tdDish) { const receiverVal = tdReceiver.textContent.toUpperCase(); const dishVal = tdDish.textContent.toUpperCase(); // 两个条件都满足才显示 const matchReceiver = !receiverFilter || receiverVal === receiverFilter; const matchDish = !dishFilter || dishVal === dishFilter; tr[i].style.display = matchReceiver && matchDish ? "" : "none"; } } } </script> </body> </html>
逻辑说明
每次任意下拉框选项变动时,都会重新读取两个筛选维度的选中值,对表格每一行数据同时做校验:
- 如果该维度选中的是
全部,则该维度直接匹配通过 - 如果该维度选中了具体值,则行内对应字段必须和选中值完全相等才算匹配通过
- 只有所有维度都匹配通过的行才会显示,否则隐藏,自动实现多条件叠加筛选的效果。
内容的提问来源于stack exchange,提问作者A. Chithrai
相关产品推荐
相关产品推荐

