
本文详解如何利用 _hyperscript 快速、可靠地实现表格中“全选/取消全选”复选框功能,支持双向同步(点击全选框统一控制,点击子项自动更新全选状态),避免常见逻辑陷阱。
本文详解如何利用 _hyperscript 快速、可靠地实现表格中“全选/取消全选”复选框功能,支持双向同步(点击全选框统一控制,点击子项自动更新全选状态),避免常见逻辑陷阱。
在构建数据表格时,“全选/反选”是高频交互需求。_hyperscript 以简洁声明式语法显著降低实现复杂度,但需注意两点核心:统一标识子复选框(推荐用 name 属性)和双向状态同步逻辑。以下为生产就绪的完整方案。
✅ 正确做法:基于 name 的全选控制(推荐)
为所有目标复选框设置相同 name(如 larm),并在“全选”复选框中使用 set <input[name='xxx']/>'s checked to my.checked 一行指令完成批量操作:
<table id="larmlista" class="table table-zebra">
<thead>
<tr>
<th>
<input type="checkbox" class="checkbox checkbox-sm"
_="on click set <input[name='larm']/>'s checked to my.checked"/>
</th>
<th>Plats</th>
<th>Namn</th>
<th>Ip</th>
</tr>
</thead>
<tbody>
<tr>
<th><input type="checkbox" class="checkbox checkbox-sm" name="larm"/></th>
<td>Office</td>
<td>Thing1</td>
<td>10.102.0.1</td>
</tr>
<tr>
<th><input type="checkbox" class="checkbox checkbox-sm" name="larm"/></th>
<td>Backyard</td>
<td>Thing2</td>
<td>10.102.0.23</td>
</tr>
<tr>
<th><input type="checkbox" class="checkbox checkbox-sm" name="larm"/></th>
<td>Kitchen</td>
<td>Thing3</td>
<td>10.102.0.16</td>
</tr>
</tbody>
</table>✅ 优势:语义清晰、无 JS 干扰、天然支持表单提交、兼容性好。
? 补充:子项变更时自动更新全选框状态
仅靠单向控制无法满足“取消任一子项 → 全选框自动取消”的体验。需添加子项监听逻辑:
<script type="text/hyperscript">
def updateSelectAll()
set $selectAll to <input[name='larm_all']/>
set $allChecked to true
for $cb in <input[name='larm']/>
if not $cb.checked then
set $allChecked to false
exit for
end
end
set $selectAll.checked to $allChecked
end
-- 绑定到每个子复选框
on click from <input[name='larm']/>
call updateSelectAll()
end
</script>并为全选框添加 name="larm_all":
<input type="checkbox" class="checkbox checkbox-sm" name="larm_all"
_="on click set <input[name='larm']/>'s checked to my.checked"/>⚠️ 注意事项:
- 避免使用 next <input/> 等模糊定位(如原始代码中的 get #larmlista then add @checked to the next <input/>),易受 DOM 结构变动影响;
- 不要依赖 id 或索引遍历,<input[name='xxx']/> 是最健壮的选择器;
- _hyperscript 中 my.checked 指当前触发事件元素的状态,me 已弃用,统一用 my;
- 若必须用 class 标识(如无法修改 name),可改用 set .foo.checked to my.checked,但需确保 class 唯一且不与其他组件冲突。
最终效果:点击“全选”框 → 所有 name="larm" 复选框同步勾选/取消;任意取消一个子项 → 全选框自动变为未勾选;全部勾选后 → 全选框自动回勾。逻辑闭环,零 bug。

















