如何用jQuery实现表格Sample列复选框的互斥禁用功能
解决Sample列复选框的互斥禁用问题
我明白你的需求啦——就是Sample列里的复选框,选了一个之后,这列其他的都不能选,取消选中后全部恢复可用。你之前的代码问题在于把所有复选框都纳入了处理范围,而且重复使用了id="sam"(id在页面里必须唯一哦),咱们来一步步修正:
第一步:修正表格生成代码
先给Sample列的复选框加一个专属的类名(比如sample-checkbox),去掉重复的id,这样能精准定位到目标元素:
for(var i=1;i<=10;i++) { var row = "<tr class='active' style='font-size:10px;height:3px;'>" + "<td style='height:3px;' class='text-center'><input type='text' name='txtQuantity' class='form-control' /></td>" + "<td style='height:3px;' class='text-center'><input type='text' name='txtQuantity' class='form-control' /></td>" + "<td style='height:3px;' class='text-center'><input type='checkbox' value=''></td>" + "<td style='height:3px;' class='text-center'><input type='checkbox' value=''></td>" + "<td style='height:3px;' class='text-center'><input type='checkbox' class='sample-checkbox' value=''></td>" + "</tr>"; $('#tblComponent tbody').append(row); }
第二步:编写精准的事件处理逻辑
现在只监听sample-checkbox类的复选框,并且只操作同一列的其他复选框:
$(document).on("change", ".sample-checkbox", function() { // 获取当前复选框所在的列(Sample列)的所有同类型复选框 const allSampleCheckboxes = $(".sample-checkbox"); if ($(this).is(":checked")) { // 禁用当前列除了自己之外的所有Sample复选框 allSampleCheckboxes.not(this).prop("disabled", true); } else { // 取消勾选时,恢复当前列所有Sample复选框的可用状态 allSampleCheckboxes.prop("disabled", false); } });
关键说明
- 用
change事件替代click:更贴合复选框的状态变化逻辑,避免点击复选框外的区域触发不必要的操作。 - 使用
prop()而非attr():对于表单元素的状态(比如disabled),jQuery推荐用prop()来设置,比attr()更可靠。 - 精准选择范围:通过
$(".sample-checkbox")只定位Sample列的复选框,不会影响其他列的元素。
把这些代码替换你原来的对应部分,就能实现你想要的效果啦!
内容的提问来源于stack exchange,提问作者Asifuzzaman
相关产品推荐
相关产品推荐

