jQuery: See how many elements a selector matched?

99封情书 提交于 2019-12-22 01:24:19

问题


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?


回答1:


call .length on the returned set.

Do not use .size because:

The .size() method is deprecated as of jQuery 1.8




回答2:


How many:

var count = $('.active').length;

Check if it matched something:

if ($('.active').length) // since 0 == false



回答3:


You can use the native javascript length property:

alert( $(".active").length );

You can even use the .length return value directly within a conditional statement:

if( $(".active").length ) {
  alert("Found some");  
} else {
  alert("Found nothing"); 
}​

In this example, if 0 results are found the else statement will be executed.

Example: http://jsbin.com/upabu/edit




回答4:


you should use $('.class').length because it is faster, but alternatively you can call $('.class').size() and get the same result.

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.



来源:https://stackoverflow.com/questions/2838518/jquery-see-how-many-elements-a-selector-matched

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!