简体   繁体   English

jQuery如果所有子项都隐藏,则隐藏父块

[英]jQuery hide parent block if all childs hidden

The question is how to hide parent block if all childs are hidden, and display it if they are visible again ? 问题是,如果所有子项都被隐藏,如何隐藏父块,如果再次可见,则如何显示 Is it possible to "monitor" block status with jQuery? 是否可以使用jQuery“监视”阻止状态?

jsFiddle example - here red block must automatically hide if we hide yellow and green blocks. jsFiddle示例 -如果我们隐藏黄色和绿色块,则红色块必须自动隐藏。

Html HTML

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

CSS 的CSS

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

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

.child2 {
    background:green;
}

JavaScript 的JavaScript

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

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

Try 尝试

$(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()
        }
    });
});

Demo: Fiddle 演示: 小提琴

You can check the length of visible elements inside #mother div by using :visible selector along with .length , if it's equal to 0 then hide #mother : 您可以使用:visible选择器和.length来检查#mother div中可见元素的长度,如果它等于0则隐藏#mother

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

Fiddle Demo 小提琴演示

Try this in child click event handlers: 在子点击事件处理程序中尝试以下操作:

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

Working Demo 工作演示

You can try so: 您可以尝试这样:

$(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();
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM