0

如果所有子跨度都有隐藏类,我正在尝试隐藏父 DIV。我的文档中还有其他具有相同类的 div 具有一两个隐藏跨度,但我只想在所有三个孩子都具有隐藏类时隐藏父 div。

这是我的 HTML:

<div class="example">
<span class="hidden">Design</span>
<span class="hidden">Development</span>
<span class="hidden">Branding</span>
</div>

如果有任何具有可见类的 span 元素,我不想隐藏父 Div。因此,如果以下情况属实:

<div class="example">
<span class="visible">Design</span>
<span class="hidden">Development</span>
<span class="visible">Branding</span>
</div>

示例 div 应该仍然可见。只有当所有三个子跨度都具有隐藏类时,它才应该是可见的。

这是我尝试过的 jQuery:

$('.example').each(function(){
if($('.hidden')(':visible').length == 0) {
$('.example').hide();
}
});

不用说,它没有奏效。

编辑:选择器已更改-我已将示例更新为更通用。

4

4 回答 4

0

试试这种方式,如果父 div 类是 'example'

$(document).ready(function (){
   $('div.example .hidden').each(function(){
    $(this).parent().hide();
    });
});

根据您的第二个解释,我进行了以下更改以适应您的要求

$(document).ready(function(){
    var count = 0;
    $('div.example .hidden').each(function(){ //take the count of hidden span tags
    count++;
    });
    $('div.example').children().each(function(){
     if($('div.example').children().length==count){  // check whether the count of hidden span tag element length is equal to all the child element length
       $('div.example .hidden').parent().hide();
       }else{
           //alert('There is an visible element');
            }
    });
});
于 2013-04-21T16:57:31.750 回答
0

鉴于该 HTML,我建议:

$('.example').each(function(){
    var that = $(this).find('.hidden');
    return that.length === that.not(':visible').length;
});

JS 小提琴演示

这假定该.example元素是您所指的相关父元素。

或稍微替代的方法:

$('.example').css('display',function(){
    var children = $(this).children();
    return children.length === children.not(':visible').length ? 'none' : 'block';
});

JS 小提琴演示

参考:

于 2013-04-21T16:54:30.873 回答
0

此答案假定如您的示例中所述,您正在寻找 .example 父容器的所有 3 个元素都具有 .hidden 类的情况。

var childElements = $('.example .hidden');

if (childElements.length === 3) {
    $('.example').hide();
}

*更新:第一个示例仅适用于只有一个 '.example' 元素的情况。以下示例分别循环遍历每个“.example”元素。

var parents = $('.example');

// Loop through each parent element, finding only it's childeren
parents.each(function(index, item) {

    var $item = $(item),
        childElements = $item.find('.hidden');

    if (childElements.length === 3) {
        $item.hide();
    }
});
于 2013-04-21T17:10:03.810 回答
0

这篇文章超级老了,但由于某种原因它突然出现在我的提要中,所以我仍然会给我两分钱:

$('.example').each(function(){
  let $parent = $(this);
  if($parent.find('span').length === $parent.find('span.hidden').length) {
    $parent.hide();
  }
});
于 2018-05-02T22:21:38.133 回答