jquery $('.class').each() how many items?
When looping over a group of items using jquery selectors is there a way to find out how many items there are on 开发者_开发问答the collection?
If you're using chained syntax:
$(".class").each(function() {
// ...
});
...I don't think there's any (reasonable) way for the code within the each
function to know how many items there are. (Unreasonable ways would involve repeating the selector and using index
.)
But it's easy enough to make the collection available to the function that you're calling in each
. Here's one way to do that:
var collection = $(".class");
collection.each(function() {
// You can access `collection.length` here.
});
As a somewhat convoluted option, you could convert your jQuery object to an array and then use the array's forEach
. The arguments that get passed to forEach
's callback are the entry being visited (what jQuery gives you as this
and as the second argument), the index of that entry, and the array you called it on:
$(".class").get().forEach(function(entry, index, array) {
// Here, array.length is the total number of items
});
That assumes an at least vaguely modern JavaScript engine and/or a shim for Array#forEach
.
Or for that matter, give yourself a new tool:
// Loop through the jQuery set calling the callback:
// loop(callback, thisArg);
// Callback gets called with `this` set to `thisArg` unless `thisArg`
// is falsey, in which case `this` will be the element being visited.
// Arguments to callback are `element`, `index`, and `set`, where
// `element` is the element being visited, `index` is its index in the
// set, and `set` is the jQuery set `loop` was called on.
// Callback's return value is ignored unless it's `=== false`, in which case
// it stops the loop.
$.fn.loop = function(callback, thisArg) {
var me = this;
return this.each(function(index, element) {
return callback.call(thisArg || element, element, index, me);
});
};
Usage:
$(".class").loop(function(element, index, set) {
// Here, set.length is the length of the set
});
Use the .length
property. It is not a function.
alert($('.class').length); // alerts a nonnegative number
If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.
However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.
You mean like length
or size()
?
Refs: http://api.jquery.com/length/
精彩评论