如何使用两个按钮实现表格Type列的Aquatic与非Aquatic内容筛选
表格Type列筛选实现方案
你可以通过原生JavaScript遍历表格行、匹配Type列内容的方式实现需求,完整代码如下:
<button type="button" onclick="Aquatic()">仅显示水生类</button> <button type="button" onclick="NotAquatic()">显示非水生类</button> <table class="table"> <thead> <tr> <th scope="col">动物</th> <th scope="col">类型</th> </tr> </thead> <tbody id="animalTbody"> <tr> <td>蝙蝠</td> <td>飞行动物</td> </tr> <tr> <td>鱼</td> <td>Aquatic</td> </tr> <tr> <td>马</td> <td>陆生动物</td> </tr> <tr> <td>鲨鱼</td> <td>Aquatic</td> </tr> <tr> <td>大象</td> <td>陆生动物</td> </tr> <tr> <td>鲸鱼</td> <td>Aquatic</td> </tr> <tr> <td>鸽子</td> <td>飞行动物</td> </tr> </tbody> </table> <script> function Aquatic() { // 获取所有表格行 const rows = document.querySelectorAll('#animalTbody tr'); rows.forEach(row => { // 取第二列(Type列)的内容,去除前后空格 const type = row.children[1].textContent.trim(); // 匹配到水生类则显示,否则隐藏 row.style.display = type === 'Aquatic' ? 'table-row' : 'none'; }); } function NotAquatic() { const rows = document.querySelectorAll('#animalTbody tr'); rows.forEach(row => { const type = row.children[1].textContent.trim(); // 匹配到非水生类则显示,否则隐藏 row.style.display = type !== 'Aquatic' ? 'table-row' : 'none'; }); } </script>
代码说明
- 给表格tbody新增了id
animalTbody,方便快速定位DOM节点 - 两个筛选函数均通过遍历行、匹配Type列内容的方式控制行的显示状态
- 匹配时做了去除前后空格的处理,避免内容两端的空白字符影响判断
内容的提问来源于stack exchange,提问作者Cecilia4585
相关产品推荐
相关产品推荐

