如何使用Hyperscript实现复选框全选功能?
解决Hyperscript全选复选框失效问题
你遇到的问题根源是直接操作了HTML的checked属性(attribute),而非DOM元素的checked属性(property)。复选框的选中状态由DOM对象的checked property控制,HTML属性仅用于初始化状态,所以直接添加checked属性会导致checked="undefined"的异常,且后续无法正确更新状态。
修复后的全选代码
<p><strong><span _="on change from <input[name='test']/> or load put (<input[name='test']:checked/>).length into me"></span></strong> selected</p> <button _="on click set property checked to true on <input[name='test']/>">Select All</button> <input type="checkbox" name="test" /> <input type="checkbox" name="test" /> <input type="checkbox" name="test" /> <input type="checkbox" name="test" /> <script src="https://unpkg.com/hyperscript.org@0.9.11"></script>
核心修改说明
将按钮的Hyperscript逻辑从add @checked替换为set property checked to true on <input[name='test']/>,这样直接操作DOM元素的checked property,确保复选框能正确响应选中状态的变更。
进阶:实现全选/取消全选切换
如果需要按钮具备切换全选/取消的功能,可以使用以下逻辑:
<button _="on click set allCheckboxes to <input[name='test']/> set shouldCheck to not (allCheckboxes[0].checked and allCheckboxes.every(box => box.checked)) set property checked to shouldCheck on allCheckboxes">Toggle Select All</button>
这段代码会先判断当前是否所有复选框都已选中,再反向设置所有复选框的状态,实现一键切换。
内容的提问来源于stack exchange,提问作者Tiago
相关产品推荐
相关产品推荐

