使用jQuery动态检查和取消选中复选框:bug?

我制作了一个脚本来控制主从复选框(自动检查和取消选中)。

这是我的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:

   Checkbox Master
  Checkbox Slave 1
  Checkbox Slave 2

看看我简单的JsFiddle来理解这个问题。

编辑1:像Inser一样说,问题发生在jQuery 1.9.2及更高版本上。 没有jQuery 1.8.3的更多问题。 奇怪…

编辑2: Inser找到解决方案,使用.prop(’checked’,true)代替.attr(’checked’,true) 。 看看下面的评论……

对新版本的jQuery使用prop方法:

 $('#myCheck').prop('checked', true); $('#myCheck').prop('checked', false); 

http://jsfiddle.net/uQfMs/37/

你可以试试这个。

 $('#myCheck').click(function() { var checkBoxes = $(this).siblings('input[type=checkbox]'); checkBoxes.prop('checked', $(this).is(':checked') ? true : false); }); 

也许您只想检查主复选框:

 $('#myCheck').click(function() { $('.myCheck').attr('checked', false); $(this).attr('checked', true); }); 

看到这个小提琴 。

我做了一些经验,实际上是$(':checkbox').attr('checked',false); 虽然这可以设置“已检查”属性,但它不会继续在视觉中显示。 和$(':checkbox').prop('checked', true); 这一个完美! 希望这可以提供一些帮助。

我为你写了一个插件:

 $.fn.dependantCheckbox = function() { var $targ = $(this); function syncSelection(group, action) { $targ.each(function() { if ($(this).data('checkbox-group') === group) { $(this).prop('checked', action); } }); }; $('input[type="checkbox"][data-checkbox-group]').on('change', function() { var groupSelection = $(this).data('checkbox-group'); var isChecked = $(this).prop('checked'); syncSelection(groupSelection, isChecked); }); } $('input[type="checkbox"][data-checkbox-group]').dependantCheckbox();         

http://codepen.io/nicholasabrams/pen/mJqyqG