使用类名 jquery 计算可见的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4663278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:40:37  来源:igfitidea点击:

counting visible divs with class name jquery

jquery

提问by metalhawk

I'm having trouble using the :visiblewith class name.

我在使用:visiblewith 类名时遇到问题。

Example:

例子:

<div class="groupedDiv" id="group1">
    <div class="level1">
        Apples
        <div class="level2"> || L2-apple </div>
    </div>

    <div class="level1" style="display:none;">
        Oranges 
        <div class="level2"> || [L2-orange] </div>
    </div>
</div>

<br/>

<div class="groupedDiv" id="group1">
    <div class="level1">
        Roses
        <div class="level2"> || L2-rose </div>
        <div class="level3"> l3 rose </div>
    </div>
</div>

If I want to count the # of visible divs of class level1

如果我想计算类的可见 div 的数量 level1

$(".level1 :visible").length;gives me output 3, doesn't this supposed to output 2 ?

$(".level1 :visible").length;给我输出 3,这不是应该输出 2 吗?

$(".level1 :visible").parent().length;gives me output 2 which is correct.

$(".level1 :visible").parent().length;给我输出 2,这是正确的。

I have created this example at http://jsfiddle.net/metalhawk/P87jS/

我在http://jsfiddle.net/metalhawk/P87jS/创建了这个例子

Any suggestions are helpful. Thanks

任何建议都是有帮助的。谢谢

回答by lonesomeday

$(".level1 :visible")is a descendant selector: you are selecting all visible elements that are descendants of .level1. There are three divelements that are visible beneath .level1elements.

$(".level1 :visible")是后代选择器:您正在选择.level1. 在div元素下方可见三个.level1元素。

Use this instead:

改用这个:

$(".level1:visible").length;

See your fiddle per my update.

根据我的更新查看您的小提琴

回答by dpmguise

Pretty sure you need to do $(".level1:visible").length;

很确定你需要做 $(".level1:visible").length;

the Space is breaking the code

空间正在破坏代码