Use jQuery to check if all div's are hidden

Asked
Viewd30754

16

How would I check if all the div's with class test are hidden. And if they are all hidden set wrap1 to hidden. Thanks.

<div id='wrap1'>
<div class="header">Header 1</div>
<div class='test'><a href="#">Test 1</a></div>
<div class='test'><a href="#">Test 2</a></div>
<div class='test'><a href="#">Test 3</a></div>
</div>

UPDATE: Thanks everyone for the really quick answers, I got it working. They were all very helpful.

4 个答案

36

您可以使用上面建议的选择器进行检查,如下所示:

  if ( $("div.test:visible").length === 0)
      $("#wrap1").hide( );
 
0

查看它们是否全部可见的更好方法是可见性计数与总计数相同。

 $("#wrap1 div:visible").length == $("#wrap1 div").length
 
  • You need to qualify this with the appropriate class test. According to the OP the wrapper should be hidden if the “testN” classed DIVs are hidden even if the “header” DIV isn’t.

    tvanfossonAugust 03, 2009 15:28
0
 jQuery("#wrap1").find("div").each(function()
   {
      if ($(this).is(':hidden'))
      {
      }
   }
);
 
8

此代码段将循环所有<div id="wrap#">,如果测试被隐藏则将其隐藏。

 $("div[id^='wrap']").each(function() {
  var wrap = $(this);

  if(wrap.children("div[class^='test']:visible").length == 0) {
    wrap.hide();
  } else {
    wrap.show();
  }
});
 

如果您根本不想进行任何测试(如标记中的任何一项),但仍希望保持<div id="wrap#">可见,则可以使用以下修改后的代码段:

 $("div[id^='wrap']").each(function() {
  var wrap = $(this);

  if(wrap.children("div[class^='test']").length > 0 && 
     wrap.children("div[class^='test']:visible").length == 0) {
    wrap.hide();
  } else {
    wrap.show();
  }
});
 

没有任何令人信服的理由对数字进行分类(除了在极端情况下)。您的编号使上面的代码以及CSS变得复杂。仅从test中删除编号会更容易。(您不需要它,因为您始终可以使用:lt(index):gt(index):eq(index):first:last选择其中的一个子集。

对于编号ID,这很好,因为每个ID必须是唯一的。

  • @tvanfosson: Maybe, anyway, comparing the :hidden length to the :visible length won’t work as both will return 0 if there are no elements.

    Andrew MooreAugust 03, 2009 15:29
  • @Andrew – I’m not sure. There’s a semantic difference between “there are no results” and “all of the results are hidden”. I’m not saying your answer is wrong, just pointing out that behavior applies in more than just the all are hidden case.

    tvanfossonAugust 03, 2009 15:25
  • @tvanfosson: Technically if there are no div.test in the markup, it is the same as having no div.test visible. I’m pretty sure that desired behavior.

    Andrew MooreAugust 03, 2009 15:22
  • If you only wanted the behavior when there were divs but they were all hidden, you could check to make sure the :hidden count is the same as the :visible count.

    tvanfossonAugust 03, 2009 15:23
  • Note that this would also hide the wrapper div if there were no divs with a matching class. Not sure if that’s desired behavior or not.

    tvanfossonAugust 03, 2009 15:21