javascript 使用 jQuery 计算可见的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19381621/
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-10-27 15:22:29  来源:igfitidea点击:

Count visible divs with jQuery

javascriptjqueryhtmljquery-selectors

提问by Daniel W.

HTML:

HTML:

<div class="male">...</div>
<div class="male">...</div>
<div class="female">...</div>

I have several divs with categories as class (and more divs without .maleinside of them), on startup I count them with

我有几个类别为类的 div(还有更多没有.male在它们内部的div ),在启动时我用

$('.male').size(); // Returns 40 items for example

(I know size();is deprecated but we use an older version of jQuery)

(我知道size();不推荐使用,但我们使用旧版本的 jQuery)

During the application, some of the divs turn invisible after a specific click, I want to recount the visibleitems.

在应用过程中,某些div在特定单击后变为不可见,我想重新计算可见项。

I tried

我试过

$('.male :visible').size();

But it gave me a horrible high number, like 3050, so I assume the selector does count all the visible divs inside .maleor something.

但它给了我一个可怕的高数字,比如 3050,所以我假设选择器确实计算了里面的所有可见 div.male或其他东西。

Is someone able to advice me the correct selector for only visible divs with specific class?

有人能够建议我正确的选择器只针对具有特定类的可见 div 吗?

回答by James Donnelly

You need to remove the space between .maleand :visible, otherwise you're targeting all visible elements within.male:

您需要删除之间的空间.male:visible,否则你的目标所有可见的元素.male

$('.male:visible').size();

Here's a quick JSFiddle demoshowing both.

这是一个快速的 JSFiddle 演示,显示了两者。

UPDATE:jQuery 1.8 deprecated its size()method in favour of using JavaScript's lengthproperty instead. We can now:

更新:jQuery 1.8 弃用了它的size()方法,转而使用 JavaScript 的length属性。我们现在可以:

$('.male:visible').length;

回答by tymeJV

Remove the space from your selector:

从选择器中删除空格:

$('.male:visible').size();