使用 jQuery 计算元素

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

Count elements with jQuery

jquery

提问by santa

Is there a way to count how many elements on the page with a particular class?

有没有办法用特定的类来计算页面上有多少元素?

回答by David

$('.someclass').length

You could also use:

您还可以使用:

$('.someclass').size()

which is functionally equivalent, but the former is preferred. In fact, the latter is now deprecatedand shouldn't be used in any new development.

这在功能上是等效的,但前者是首选。事实上,后者现已弃用,不应在任何新开发中使用。

回答by David Houde

var count_elements = $('.class').length;

From: http://api.jquery.com/size/

来自:http: //api.jquery.com/size/

The .size() method is functionally equivalent to the .length property; however, the .length property is preferred because it does not have the overhead of a function call.

.size() 方法在功能上等同于 .length 属性;然而,首选 .length 属性,因为它没有函数调用的开销。

Please see:

请参见:

http://api.jquery.com/size/

http://api.jquery.com/size/

http://api.jquery.com/length/

http://api.jquery.com/length/

回答by g.d.d.c

Yes, there is.

就在这里。

$('.MyClass').size()

回答by IronicMuffin

I believe this works:

我相信这有效:

$(".MyClass").length 

回答by Naftali aka Neal

try this:

尝试这个:

var count_element = $('.element').length

回答by Panomosh

The best way would be to use .each()

最好的方法是使用.each()

var num = 0;

$('.className').each(function(){
    num++;
});

回答by Kiss Koppány

$('.class').length

This one does not work for me. I'd rather use this:

这个对我不起作用。我宁愿使用这个:

$('.class').children().length

I don't really know the reason why, but the second one works only for me. Somewhy, either size doesn't work.

我真的不知道原因,但第二个只对我有用。不知何故,任何一种尺寸都不起作用。

回答by neebz

use the .size()method or .lengthattribute

使用.size()方法或.length属性