如何点击国家按钮隐藏表格中非对应国家的行
实现点击按钮隐藏非对应国家表格行的解决方案
1. 补全按钮HTML代码
首先需要添加对应的国家按钮(建议增加「显示所有行」按钮提升用户体验):
<button id="Brazil">Brazil</button> <button id="Argentina">Argentina</button> <button id="Bolivia">Bolivia</button> <button id="ShowAll">显示所有行</button> <table id="table"> <tr> <th>league</th> <th>level</th> <th>country</th> </tr> <!-- 表格数据行示例 --> <tr> <td>Serie A</td> <td>1</td> <td>Brazil</td> </tr> <tr> <td>Primera Division</td> <td>1</td> <td>Argentina</td> </tr> </table>
2. 修改jQuery逻辑
替换原有的点击事件代码,实现「隐藏非目标国家行+高亮目标行」的逻辑:
$(document).ready(function() { // 绑定所有国家按钮的点击事件 $("#Brazil, #Argentina, #Bolivia").click(function() { const targetCountry = $(this).attr("id"); const $dataRows = $("#table tr:not(:first)"); // 排除表头行 // 先重置所有行的显示状态 $dataRows.show(); // 遍历行,隐藏不匹配的行,高亮匹配行 $dataRows.each(function() { const rowCountry = $(this).find("td:nth-child(3)").text().trim(); if (rowCountry !== targetCountry) { $(this).hide(); } else { // 移除其他高亮类,添加当前国家的高亮类 $(this).removeClass("argentina bolivia brazil") .addClass(targetCountry.toLowerCase()); } }); }); // 显示所有行的重置按钮逻辑 $("#ShowAll").click(function() { $("#table tr:not(:first)") .show() .removeClass("brazil argentina bolivia"); }); });
3. 保留原有样式(可选)
原有的高亮样式可以继续使用,用来突出显示保留的行:
.brazil { background-color: yellow; } .argentina { background-color: red; } .bolivia { background-color: blue; } .peru { background-color: green; }
关键说明
- 统一匹配逻辑:确保表格中
country列的文本与按钮id完全一致(若需忽略大小写,可将对比逻辑改为rowCountry.toLowerCase() === targetCountry.toLowerCase()) - 排除表头:通过
:not(:first)避免操作表头行,保证表头始终显示 - 状态重置:每次点击按钮先显示所有行,避免之前的隐藏状态干扰当前操作
内容的提问来源于stack exchange,提问作者R9ronaldo
相关产品推荐
相关产品推荐

