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

如何实现仅勾选表格中未隐藏行的所有复选框?

解决方法

要实现仅勾选未隐藏行的复选框,只需修改toggle函数,在遍历复选框时判断其所在行是否可见即可,同时可以优化DOM查询效率。

修改后的完整代码如下:

function toggle(source) {
    // 获取表格tbody中的所有行
    const rows = document.querySelector('#tblEmployees tbody').querySelectorAll('tr');
    rows.forEach(row => {
        // 检查当前行是否可见(display不为none)
        if (row.style.display !== 'none') {
            const checkbox = row.querySelector('input[name="cbox"]');
            if (checkbox) {
                checkbox.checked = source.checked;
            }
        }
    });
}

function FilterTable() {
    const input = document.getElementById("txtFilter");
    const filter = input.value.toUpperCase();
    const table = document.getElementById("tblEmployees");
    const tr = table.querySelectorAll('tbody tr'); // 优化:只查询tbody的行

    tr.forEach(row => {
        const td = row.querySelector('td:nth-child(2)');
        if (td) {
            const txtValue = td.textContent || td.innerText;
            row.style.display = txtValue.toUpperCase().includes(filter) ? "" : "none";
        }
    });
}
<input type="text" id="txtFilter" onkeyup="FilterTable()"  />
 <table id="tblEmployees">
    <thead>
        <tr>
            <th><input type="checkbox" onClick="toggle(this)"></th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
        <td><input type="checkbox" name="cbox"/></td>
        <td>John 1</td>
        </tr>
        <tr>
        <td><input type="checkbox" name="cbox"/></td>
        <td>John 2</td>
        </tr>
        <tr>
        <td><input type="checkbox" name="cbox"/></td>
        <td>John 3</td>
        </tr>
        <tr>
        <td><input type="checkbox" name="cbox"/></td>
        <td>Mark 1</td>
        </tr>
        <tr>
        <td><input type="checkbox" name="cbox"/></td>
        <td>Mark 2</td>
        </tr>
    </tbody>
  </table>

关键改动说明

  1. toggle函数核心修改:

    • 不再直接全局获取所有name="cbox"的复选框,而是先定位表格tbody的行元素
    • 遍历每行时,通过row.style.display !== 'none'判断行是否处于可见状态
    • 仅对可见行内的复选框同步表头复选框的状态,隐藏行的复选框保持原有状态不变
  2. FilterTable函数优化:

    • 使用querySelectorAll('tbody tr')替代getElementsByTagName,避免误查询到表头行
    • 用includes替代indexOf > -1,代码逻辑更直观简洁

这样就能实现需求:筛选后点击表头复选框,只选中当前可见的行;清除筛选后,之前隐藏的行的复选框状态不会被修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:00:48