jquery $('.class').each()有多少项?

Hai*_*ood 39 jquery jquery-selectors

使用jquery选择器循环遍历一组项目时,有没有办法找出集合中有多少项?

T.J*_*der 97

如果您使用链式语法:

$(".class").each(function() {
    // ...
});
Run Code Online (Sandbox Code Playgroud)

...我认为each函数中的代码没有任何(合理的)方法可以知道有多少项.(不合理的方式将涉及重复选择器和使用index.)

但是很容易使集合可用于您正在调用的函数each.这是一种方法:

var collection = $(".class");
collection.each(function() {
    // You can access `collection.length` here.
});
Run Code Online (Sandbox Code Playgroud)

作为一个有点复杂的选项,您可以将jQuery对象转换为数组,然后使用数组forEach.传递给forEach回调的参数是被访问的条目(jQuery为您提供的内容this第二个参数),该条目的索引以及您调用它的数组:

$(".class").get().forEach(function(entry, index, array) {
    // Here, array.length is the total number of items
});
Run Code Online (Sandbox Code Playgroud)

这假定至少是一个模糊的现代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);
    });
};
Run Code Online (Sandbox Code Playgroud)

用法:

$(".class").loop(function(element, index, set) {
    // Here, set.length is the length of the set
});
Run Code Online (Sandbox Code Playgroud)