如果未选中一个子项,请取消选中父复选框

我正在开发一个需要多个复选框值的应用程序。 我有嵌套列表包含复选框。 目前的function是这样的:

  1. 选中父级时,将在其下检查所有子级。
  2. 选中子项时,不选择父项。

我需要添加此function:

  1. 如果在选中父项后取消选中子项,则父项将取消选中,但会保留子项。

    $('input[name="level-1"],input[name="level-2"]').bind('click', function () { $('input[type=checkbox]', $(this).parent('li')).attr('checked', ($(this).is(':checked'))); });

我的代码在这里找到: http : //jsfiddle.net/dbcottam/Py4UN/

可能的解决方案

然后将类someclass添加到最顶层的ul元素

 $('.someclass :checkbox').bind('click', function () { var $chk = $(this), $li = $chk.closest('li'), $ul, $parent ; if($li.has('ul')){ $li.find(':checkbox').not(this).prop('checked', this.checked) } do{ $ul = $li.parent(); $parent = $ul.siblings(':checkbox'); if($chk.is(':checked')){ $parent.prop('checked', $ul.has(':checkbox:not(:checked)').length == 0) } else { $parent.prop('checked', false) } $chk = $parent; $li = $chk.closest('li'); } while($ul.is(':not(.someclass)')); }); 

演示: 小提琴

我尝试了一个通用函数来处理多个级别。 见下面的代码,

 $('input[name^="level"]').click(function () { //v-- Takes care of check/uncheck all child checkbox $(this).parent().find('input[name^=level]').prop('checked', this.checked); if (!this.checked) { var level = this.name.substring(this.name.length - 1); //using the naming convention `level-n` to uncheck parent for (var i = level - 1; i > 0; i--) { $('input[name="level-' + i + '"]').prop('checked', false); } } }); 

演示: http //jsfiddle.net/46hTc/