如果隐藏了所有子节点,jQuery会隐藏父块

时间:2014-04-10 06:58:30

标签: javascript jquery html css

问题是如果隐藏所有孩子,如何隐藏父块,如果再次可见则显示? 有可能"监控"使用jQuery阻止状态?

jsFiddle example - 如果我们隐藏黄色和绿色块,红色块必须自动隐藏。

HTML

<div id="mother">
    <div class="child1"></div>
   <div class="child2"></div>
</div>

CSS

#mother {
    width:200px;
    height:200px;
    background:red;
}

.child1, .child2 {
    width:100px;
    height:100px;
    background: orange;
}

.child2 {
    background:green;
}

的JavaScript

$(function() {
    var childs = $("[class^=child]");

    childs.click(function() {
        $(this).hide();
    });
});

4 个答案:

答案 0 :(得分:3)

尝试

$(function () {
    var childs = $("[class^=child]");

    childs.click(function () {
        $(this).hide();
        //check if any child is visible, if not hide the mother element
        if(!childs.filter(':visible').length){
            $('#mother').hide()
        }
    });
});

演示:Fiddle

答案 1 :(得分:2)

您可以使用 :visible 选择器和#mother检查.length div中可见元素的长度,如果它等于0然后隐藏#mother

$(function () {
    var childs = $("[class^=child]");
    childs.click(function () {
        $(this).hide();
        if ($("#mother").find(":visible").length == 0) 
            $("#mother").hide();
    });
});

<强> Fiddle Demo

答案 2 :(得分:1)

在子点击事件处理程序中尝试此操作:

   if($('#mother').children(':visible').length == 0) {
      $('#mother').hide();
   }

<强> Working Demo

答案 3 :(得分:0)

您可以尝试:

$(function() {
    var childs = $("[class^=child]");

    childs.click(function() {
        $(this).hide();
        var $parent = $(this).parent();
        var $child = $parent.find('div:visible');

        if(!$child.length){
           $parent.hide();
        }
    });
});