You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现仅显示包含单选按钮对应值的表格行?

当然可以帮你实现这个功能!下面是完整的解决方案,包含HTML结构调整和JavaScript函数,能实现单选按钮选中后自动过滤表格行的效果:

解决方案

1. 调整后的HTML结构

我给单选按钮补充了必要的name和value属性(保证单选互斥,同时方便获取筛选值),给表格的数据行添加了类名以便快速选择:

<!-- 单选按钮组 -->
<label><input type="radio" name="age-range" value="0-30" checked> 0-30</label>
<label><input type="radio" name="age-range" value="30-90"> 30-90</label>
<label><input type="radio" name="age-range" value="90-100"> 90-100</label>

<!-- 表格 -->
<table>
  <thead>
    <tr>
      <th>id</th>
      <th>name</th>
      <th>età</th>
    </tr>
  </thead>
  <tbody>
    <tr class="data-row">
      <td>1</td>
      <td>Sta</td>
      <td>0-30</td>
    </tr>
    <tr class="data-row">
      <td>2</td>
      <td>Danny</td>
      <td>30-90</td>
    </tr>
    <tr class="data-row">
      <td>3</td>
      <td>Elle</td>
      <td>90-100</td>
    </tr>
  </tbody>
</table>

2. JavaScript 筛选函数

下面是实现筛选逻辑的JS代码,我们通过监听单选按钮的change事件来触发筛选:

// 获取所有单选按钮和数据行
const radioButtons = document.querySelectorAll('input[name="age-range"]');
const dataRows = document.querySelectorAll('.data-row');

// 筛选函数
function filterTable() {
  // 获取当前选中的区间值
  const selectedRange = document.querySelector('input[name="age-range"]:checked').value;
  
  // 遍历所有数据行,判断是否显示
  dataRows.forEach(row => {
    // 获取当前行的età列内容
    const rowRange = row.querySelector('td:nth-child(3)').textContent.trim();
    // 匹配则显示,否则隐藏
    row.style.display = rowRange === selectedRange ? '' : 'none';
  });
}

// 给每个单选按钮绑定change事件
radioButtons.forEach(radio => {
  radio.addEventListener('change', filterTable);
});

// 页面加载时执行一次,确保初始状态正确
filterTable();

3. 功能说明

  • 页面加载完成后,会默认显示选中的0-30区间对应的行
  • 每次切换单选按钮,表格会实时更新,只显示对应区间的行
  • 代码逻辑简单易懂,你可以根据自己的实际需求调整(比如如果età列的位置变化了,修改nth-child(3)为对应的列索引即可)

内容的提问来源于stack exchange,提问作者Carla

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 00:47:29