【发布时间】:2018-03-16 21:12:25
【问题描述】:
我编写了一个脚本来控制主从复选框(自动选中和取消选中)。
这是我的 JS:
$(document).ready(function() {
$('#myCheck').click(function() {
$('.myCheck').attr('checked', false);
});
$('.myCheck').click(function() {
if ($('.myCheck').is(':checked')) {
$('#myCheck').attr('checked', false);
} else {
$('#myCheck').attr('checked', true); // IT DOESN'T WORK, WHY ?
alert("Checkbox Master must be checked, but it's not!");
}
});
});
这是我的 HTML:
<input type="checkbox" id="myCheck" checked="checked" /> Checkbox Master<br />
<input type="checkbox" class="myCheck" value="1" /> Checkbox Slave 1<br />
<input type="checkbox" class="myCheck" value="1" /> Checkbox Slave 2
看我简单的JsFiddle就可以理解问题了。
编辑 1: 就像 Inser 所说的,问题发生在 jQuery 1.9.2 及更高版本上。 jQuery 1.8.3 不再有问题。奇怪……
EDIT 2 : Inser 找到了解决方案,使用 .prop('checked', true) 代替 .attr('checked', true)强>。看看下面的cmets...
【问题讨论】:
-
问题是什么?
-
Looking at your simple JsFiddle to understand the problem但是 myaaan!我不知道你想做什么......所以你想要什么 -
好的,对不起,我以为我的代码很清楚...事实上,一旦您单击 Checkbox Master,所有 Checkboxes Slave 必须取消选中:它工作正常。另一方面,一旦取消选中一个 Checkbox Slave 并且没有其他选中的 Checkbox Slave,则必须自动选中 Checkbox Master。对不起,我希望你现在能理解我的问题......
-
看起来是 jquery 问题。它在 1.8.3 版本中可以完美运行,但在 1.9.1 之后就不行了
-
该死的,你是对的 Inser!所以这是一个真正的 Jquery 错误...