如何根据Select控件的选项值过滤Table表格内容?
实现下拉框筛选表格行的方案
这其实用原生JavaScript就能轻松搞定,我给你整理了两种可行的实现方式,按需选择就行:
方式一:通过行类名筛选(推荐,更稳定高效)
首先我们给表格的每一行加上对应职位的类名,这样后续筛选时能快速匹配:
<table id="staffTable"> <tbody> <tr class="developer"> <td>John</td> <td>Doe</td> <td>Web Developer</td> </tr> <tr class="designer"> <td>Michael</td> <td>Doe</td> <td>Web Designer</td> </tr> <tr class="designer"> <td>Nicole</td> <td>Doe</td> <td>Graphic Designer</td> </tr> </tbody> </table> <select id="roleFilter"> <option value="all">All Staff</option> <!-- 加个全选选项,体验更友好 --> <option value="developer">Developers</option> <option value="designer">Designers</option> </select>
然后写JavaScript逻辑,监听下拉框的选择变化,控制行的显示隐藏:
// 获取下拉框和所有表格行元素 const filterSelect = document.getElementById('roleFilter'); const staffRows = document.querySelectorAll('#staffTable tbody tr'); // 监听下拉框的change事件 filterSelect.addEventListener('change', function() { const selectedRole = this.value; // 遍历每一行,根据选中的角色控制显示 staffRows.forEach(row => { if (selectedRole === 'all' || row.classList.contains(selectedRole)) { row.style.display = ''; // 显示该行 } else { row.style.display = 'none'; // 隐藏该行 } }); });
方式二:直接读取单元格内容筛选(无需修改HTML结构)
如果不想给行加类名,也可以直接读取表格第三列的职位文本进行判断,适合快速临时实现:
const filterSelect = document.getElementById('roleFilter'); const staffRows = document.querySelectorAll('#staffTable tbody tr'); filterSelect.addEventListener('change', function() { const selectedRole = this.value.toLowerCase(); staffRows.forEach(row => { // 获取第三列的职位文本,转小写方便匹配 const rowRole = row.querySelector('td:nth-child(3)').textContent.toLowerCase(); if (selectedRole === 'all' || rowRole.includes(selectedRole)) { row.style.display = ''; } else { row.style.display = 'none'; } }); });
小提示
- 方式一的类名匹配更稳定,不会因为职位文本的大小写、空格变化出问题,推荐在正式项目里使用。
- 如果需要更优雅的显示隐藏,也可以用CSS类来控制,比如定义一个
.hidden { display: none; },然后通过row.classList.toggle('hidden', 匹配条件)来切换,这样样式和逻辑分离更规范。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

