当使用 jquery 选择器循环一组项目时,有没有办法找出集合中有多少个项目?
最佳答案
如果您使用链式语法:
$(".class").each(function() {
// ...
});
...我认为 each
函数中的代码没有任何(合理的)方法来知道有多少项。 (不合理的方法包括重复选择器和使用索引
。)
但是让集合可供您在 each
中调用的函数使用是很容易的。这是一种方法:
var collection = $(".class");
collection.each(function() {
// You can access `collection.length` here.
});
作为一个有点复杂的选项,您可以将 jQuery 对象转换为数组,然后使用该数组的 forEach
。传递给 forEach
回调的参数是正在访问的条目(jQuery 为您提供 this
和第二个 参数),该条目的索引以及您调用它的数组:
$(".class").get().forEach(function(entry, index, array) {
// Here, array.length is the total number of items
});
这假设至少有一个模糊的现代 JavaScript 引擎和/或 Array#forEach
的垫片。
或者就此而言,给自己一个新工具:
// 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);
});
};
用法:
$(".class").loop(function(element, index, set) {
// Here, set.length is the length of the set
});
关于jquery $ ('.class' ).each() 有多少项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5148509/