Javascript 计算某个类的 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1899480/
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
Count divs with a certain class
提问by wesbos
Seems pretty simple but I can't get it to work.
看起来很简单,但我无法让它工作。
I have two divs with the class 'user'. I want to output "you have 2 divs".
我有两个“用户”类的 div。我想输出“你有 2 个 div”。
<script type="text/javascript">
$(document).ready(function() {
function divcount() {
var mycount = $('.user').length();
document.write(mycount)
}
});
</script>
I'm sure I'm missing something simple..
我确定我错过了一些简单的东西..
采纳答案by Yuriy Faktorovich
回答by Gumbo
It's either $('.user').length(lengthproperty of Array) or $('.user').size()(sizemethod of jQuery).
它是$('.user').length(Array 的length属性)或$('.user').size()(jQuery 的size方法)。
回答by Dave Ward
It's just $('.user').length. It's a property, not a method call.
这只是$('.user').length。它是一个属性,而不是一个方法调用。
回答by www
$(".user").length // use the length property
$(".user").size() // use the size method
notice that the code must be include in the $(function(){...}) block; like:
请注意,代码必须包含在 $(function(){...}) 块中;喜欢:
$(function(){
alert( $(".user").length );
alert( $(".user").size() );
});

