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

如何通过JavaScript实现根据复选框选中状态显示对应表格行

复选框筛选表格行实现方案

1 先修正你的HTML错误

你当前的HTML存在两个会影响功能的问题:

  • 重复嵌套了两层<thead>标签,需要删除多余的一层
  • 模板循环{% for %}的位置错误,应该包裹<tr>标签,否则所有数据会被渲染到同一行
    修正后的参考结构:
<div>Country</div>
<div class="row" name="country_checkbox" id="id_row">
 <ul id="id_country">
  <li>
    <label for="id_country_0">
      <input type="checkbox" name="country" value="NORTHAMERICA" placeholder="Select Country" id="id_country_0">
      NORTHAMERICA
    </label>
  </li>
  <li>
    <label for="id_country_3">
      <input type="checkbox" name="country" value="LATAM" placeholder="Select Country" id="id_country_3">
      LATAM
    </label>
  </li>
  <li>
    <label for="id_country_2">
      <input type="checkbox" name="country" value="ASIA" placeholder="Select Country" id="id_country_2">
      ASIA
    </label>
  </li>
 </ul>
</div>
<table class="datatable" id='table_id'> 
  <thead>
    <tr>
      <th>Region</th>
      <th>Area</th>
      <th>Country</th>
    </tr>
  </thead>
  <tbody>
    {% for i in database%}
    <tr class="data-row">
      <td>{{i.Region}}</td>
      <td>{{i.Area}}</td>
      <td>{{i.Country}}</td>
    </tr>
    {% endfor %}
  </tbody>
</table>

注:给数据行加了data-row类名方便JS选择,同时补全了Django模板变量的双花括号,你如果用的其他模板语法对应调整即可


2 编写JS筛选逻辑

直接在页面底部加入以下代码即可实现功能:

// 获取所有复选框和表格数据行
const checkboxes = document.querySelectorAll('input[name="country"]');
const tableRows = document.querySelectorAll('.data-row');

// 给每个复选框绑定状态变化事件
checkboxes.forEach(checkbox => {
  checkbox.addEventListener('change', filterTable);
});

// 筛选函数
function filterTable() {
  // 收集所有已选中的区域值
  const selectedRegions = Array.from(checkboxes)
    .filter(box => box.checked)
    .map(box => box.value);

  // 遍历所有表格行判断显示/隐藏
  tableRows.forEach(row => {
    // 获取当前行的Region列内容,去除首尾空格
    const rowRegion = row.querySelector('td:first-child').textContent.trim();
    // 没有选中项默认显示所有,有选中项则判断是否匹配
    const shouldShow = selectedRegions.length === 0 || selectedRegions.includes(rowRegion);
    row.style.display = shouldShow ? '' : 'none';
  });
}

3 逻辑调整说明

如果需要修改默认行为,可直接调整代码逻辑:

  • 如果需要无复选框选中时隐藏所有行,把selectedRegions.length === 0 ||删掉即可
  • 如果需要根据Country列而非Region列筛选,把td:first-child改成td:last-child即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:15:03