
本文详解如何用 _hyperscript 快速、可靠地实现表格中“全选/取消全选”复选框功能,支持双向同步(点击全选框统一控制,点击任意子项自动更新全选状态),避免常见逻辑陷阱。
本文详解如何用 _hyperscript 快速、可靠地实现表格中“全选/取消全选”复选框功能,支持双向同步(点击全选框统一控制,点击任意子项自动更新全选状态),避免常见逻辑陷阱。
在构建数据表格时,“全选/取消全选”是高频交互需求。_hyperscript 以其简洁声明式语法极大简化了这类 DOM 操作,但若未正确处理双向同步逻辑(如子项变更后全选框状态未及时更新),极易出现体验断裂——例如手动取消一个子项后,“全选框”仍保持勾选状态,违背用户直觉。
✅ 正确实现:单向控制 + 双向响应
最简健壮方案分两步:统一命名 + 精准选择器。为所有目标复选框添加相同 name 属性(推荐),或统一 class(备选),再通过 _hyperscript 指令批量操作。
1. 基础 HTML 结构(关键:统一 name)
<table id="larmlista" class="table table-zebra">
<thead>
<tr>
<th>
<!-- 全选框:监听 click,批量设置所有 name="larm" 的 checkbox 状态 -->
<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>2. 补充双向同步逻辑(可选但强烈推荐)
仅靠全选框单向控制不够——当用户手动勾选/取消任意子项时,全选框应自动反映整体状态(全选 → 勾选,部分选 → 不勾选,全不选 → 取消)。需添加 handleChecked 函数:
<script type="text/hyperscript">
def handleChecked(checkbox)
-- 获取所有同名复选框
set allCheckboxes to <input[name='larm']/>
-- 统计已勾选项数量
set checkedCount to 0
for cb in allCheckboxes
if cb.checked then set checkedCount to checkedCount + 1
end
-- 更新全选框状态:仅当全部勾选时才勾选全选框
if checkedCount == allCheckboxes.length then
set <input[name='larm_all']/>'s checked to true
else
set <input[name='larm_all']/>'s checked to false
end
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" />每个子项绑定事件:
<input type="checkbox" class="checkbox checkbox-sm" name="larm"
_="on click handleChecked(me)" />? 关键提示
- ✅ 务必为复选框设置 name 属性:这是 _hyperscript <input[name='xxx']/> 选择器的基石,比 class 更语义化且不易冲突。
- ⚠️ 避免使用 next <input/> 等模糊定位:原始代码中 get #larmlista then add @checked to the next <input/> 仅影响紧邻下一个元素,无法批量操作,是典型错误。
- ? 若必须用 class,请确保 class 名唯一(如 .larm-checkbox),指令改为:set .larm-checkbox.checked to my.checked。
- ? 注意:<input[name='xxx']/>'s checked 是 _hyperscript 的标准属性访问语法,不可写作 checked=true 或 @checked。
此方案兼顾简洁性与鲁棒性,无需 JavaScript 手动遍历,完全由 _hyperscript 声明式完成状态同步,符合现代前端“逻辑即配置”的开发哲学。

















