HTML Grid Table单选限制:求自定义jQuery/JavaScript实现方案
实现网格表格Checkbox单选功能(原生JS方案)
核心思路
每次点击表格中的checkbox时,遍历所有同组的checkbox,将当前点击项之外的其他checkbox设为未选中状态,强制实现单选效果。
示例HTML结构
假设弹窗内的表格结构如下:
<div class="modal"> <table class="grid-table"> <thead> <tr> <th><input type="checkbox" id="select-all"></th> <th>Full name</th> <th>Email ID</th> <th>Emp ID</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" class="row-checkbox" data-emp-id="1"></td> <td>John Doe</td> <td>john@example.com</td> <td>E001</td> </tr> <tr> <td><input type="checkbox" class="row-checkbox" data-emp-id="2"></td> <td>Jane Smith</td> <td>jane@example.com</td> <td>E002</td> </tr> <!-- 更多数据行... --> </tbody> </table> </div>
原生JS实现代码
// 在弹窗显示完成后执行(可放在弹窗触发的回调函数内) document.addEventListener('DOMContentLoaded', function() { // 获取所有行级checkbox元素 const rowCheckboxes = document.querySelectorAll('.row-checkbox'); rowCheckboxes.forEach(checkbox => { checkbox.addEventListener('change', function() { // 仅在当前checkbox被选中时,取消其他同组checkbox的选中状态 if (this.checked) { rowCheckboxes.forEach(otherCheckbox => { if (otherCheckbox !== this) { otherCheckbox.checked = false; } }); } }); }); // 可选:禁用表头全选框,避免用户混淆操作 const selectAllCheckbox = document.getElementById('select-all'); if (selectAllCheckbox) { selectAllCheckbox.disabled = true; selectAllCheckbox.title = '仅允许单选一行'; } });
关键说明
- 给所有行内checkbox统一添加类名
row-checkbox,方便批量定位元素 - 通过监听
change事件触发单选逻辑,确保仅当前点击的checkbox保持选中状态 - 禁用表头全选框是可选操作,目的是避免用户误触发批量选择,与单选规则冲突
内容的提问来源于stack exchange,提问作者Ketan
相关产品推荐
相关产品推荐

