本文介绍了如果所有子级都未在JQuery中选中,则取消选中父节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果所有子项都未选中,我想取消选中父节点.

I want to uncheck parent node if all children are unchecked.

<ul id="treeList">
   <li>
   <input type="checkbox" name="selectedRole">
   Application Manager
    <ul>
       <li>
           <input type="checkbox" name="selectedRole">
           Application Manager Panel
       </li>
       <li>
            <input type="checkbox" name="selectedRole">
            Client Role
             <ul>
               <li>
                   <input type="checkbox" name="selectedRole">
                   Client Task 1
                </li>
                <li>
                   <input type="checkbox" name="selectedRole">
                    Client Task 2
                </li>
                 </ul>
              </li>
           </ul>
       </li>

我有以下jQuery脚本.但是,当我取消选中任何孩子时,父母也取消选中.它应该查看是否所有孩子都未选中.那么它应该取消选中父项.

I have following jQuery script. But when I uncheck any children, the parent got uncheck. It should see, if all children are unchecked. then it should uncheck the parent.

jQuery.each(jQuery('#treeList ul li').find(':checkbox'),  function(){
    jQuery(this).change(function (){
        if (jQuery(this).is(':checked')) {
            jQuery(this).parents('ul').siblings('input:checkbox').attr('checked', true);
        }else{
            jQuery(this).parents('ul').siblings('input:checkbox').attr('checked', false);
        }        
    });    
});

推荐答案

每次取消选中子级时,您都在取消选中父级li复选框,而不是检查是否还有其他选中项.相反,您可以检查项目checked的数量并将该length用作boolean:

You are unchecking the parent li checkbox every time you uncheck a child, instead of checking if there's still some other checked items. Instead, you could check the number of items checked and use that length as a boolean:

jQuery.each(jQuery('#treeList ul li').find(':checkbox'),  function(){
    jQuery(this).change(function (){
        if (jQuery(this).is(':checked')) {
                      jQuery(this).parentsUntil('#treeList').siblings().filter('input:checkbox').attr('checked', true).trigger('change');
        }else{                
            jQuery(this).parents('ul:first').siblings('input:checkbox').prop('checked', $(this).parent().siblings().children('input:checked').length).trigger('change');
        }        
    });    
});

示例: http://jsfiddle.net/niklasvh/fRxVs/

这是您的提琴的更新版本...添加了一些CSS来澄清树级别(父子关系) http://jsfiddle.net/vimalpatel/fRxVs/440/

Here is your fiddle's updated version... added some CSS to clarify the Tree Level (Parent and Child Relationship ) http://jsfiddle.net/vimalpatel/fRxVs/440/

这篇关于如果所有子级都未在JQuery中选中,则取消选中父节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 00:18