从PHP中提取的目录列表中的jQuery prop父复选框


jQuery prop parent checkbox from directory listing pulled from PHP

我的目标是在嵌套列表中"支撑"父复选框。现在,我在PHP中找到一个目录列表,如下所示:

function listDirectories($dir, $i, $howDeep) {
            $lastFolder = end(explode("/", $dir));
            $listString .='<li class="closed"><span class="folder"><input type="checkbox" class="userPermissionCheckBox" parent="'.$i.'" howDeep="'.$howDeep.'" value="'.$dir.'" />'.str_replace('_', ' ', $lastFolder).'</span>';
            foreach (glob($dir."/*", GLOB_ONLYDIR) as $d) {
                $howDeep++;
                $listString .='<ul>';
                $listString .=' '.listDirectories($d, $i, $howDeep).' ';
                $listString .='</ul>';
                $i++;
                $howDeep = 1;
            }
            $listString .='</li>';
            return $listString;
        }

太棒了!,然后,我将这个jquery/js函数绑定到复选框,以在选择父框时"支撑"所有子框

 var isAlreadyChecked = $(this).prop('checked');
            $(this).parents(':eq(1)').find('.userPermissionCheckBox').each(function () {
                $(this).prop('checked', isAlreadyChecked);
            });

这也非常棒。

我遇到的问题是,如果有人在没有选中父框的情况下选中子框,它会自动选中父框。。。所以我尝试了这样的东西:

var isAlreadyChecked = $(this).prop('checked');
             var parentNumber = Number($(this).attr('parent'));
             var howDeepIsNest = Number($(this).attr('howDeep'));
            $(this).parents(':eq(1)').find('.userPermissionCheckBox').each(function () {
                $(this).prop('checked', isAlreadyChecked);
            });
            if(howDeepIsNest > 1){
                var immediateParent = howDeepIsNest - 1;
                $('.userPermissionCheckBox[howDeep='+immediateParent+']').prop('checked', true);
            }

这种方法很有效,显然子框的自动道具效果很好,但我无法让父框的自动检查工作。我愿意接受任何建议。感谢您花时间阅读本文。

这将:

  • 取消/检查所有子项
  • 检查所有家长
  • 如果同时取消选中所有同级,则取消选中直接父项

Fiddle:http://jsfiddle.net/a7WDk/1/

$('input:checkbox').on('change', function() {
    var $this = $(this),
        $lis = $this.parents('li'),
        $parents = $lis.find('> span > input:checkbox').not(this),
        $children = $lis.eq(0).find('input:checkbox').not(this),
        $related = $lis.eq(0).siblings().find('input:checkbox');
    if($this.is(':checked')) {
        $parents.add($children).attr('checked', 'checked');
    } else {
        if($children.length) {
            $children.removeAttr('checked');
        }
        if($related.length && !$related.is(':checked')) {
            $parents.eq(0).removeAttr('checked').trigger('change');
        }
    }
});