我正在开发一个需要多个复选框值的应用程序。我有包含复选框的嵌套列表。当前的功能是这样的:
- 当父级被选中时,其下的所有子级都会被选中。
- 选中子项时,不会选择父项。
我需要添加此功能:
如果在选中父级后取消选中子级,则父级会取消选中,但会保留子级的选中状态。
$('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)'));
});
演示:Fiddle
关于javascript - 如果未选中一个子项,请取消选中父项复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233624/