[英]jQuery: See how many elements a selector matched?
If I have a selector like 如果我有一个选择器
$.('.active');
How can I see how many items that matched? 如何查看匹配的项目数量?
Alternatively, is there an easy way to see if more than zero elements were matched? 或者,是否有一种简单的方法可以查看是否匹配了多于零的元素?
How many: 多少:
var count = $('.active').length;
Check if it matched something: 检查它是否匹配的东西:
if ($('.active').length) // since 0 == false
You can use the native javascript length
property: 您可以使用本机javascript
length
属性:
alert( $(".active").length );
You can even use the .length
return value directly within a conditional statement: 您甚至可以直接在条件语句中使用
.length
返回值:
if( $(".active").length ) {
alert("Found some");
} else {
alert("Found nothing");
}
In this example, if 0 results are found the else statement will be executed. 在此示例中,如果找到0结果,则将执行else语句。
Example: http://jsbin.com/upabu/edit 示例: http : //jsbin.com/upabu/edit
you should use $('.class').length
because it is faster, but alternatively you can call $('.class').size()
and get the same result. 你应该使用
$('.class').length
因为它更快,但你也可以调用$('.class').size()
并得到相同的结果。
To check the elements, do something like the following: 要检查元素,请执行以下操作:
var len = $('.class').length;
if (len)
// do something
else
// do something else
Caching the length in a local var is an optimization that will speed up your JS if you have to make another call to that length property. 在本地var中缓存长度是一种优化,如果你必须再次调用该length属性,它将加速你的JS。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.