2011-02-28 56 views
30

当使用jQuery选择器循环一组项目时,有一种方法可以找出集合上有多少项目?

回答

76

如果您使用链式语法:

$(".class").each(function() { 
    // ... 
}); 

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

但它是很容易使收集可供您已经在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 
}); 
+1

或者,将'length'值本身存储在外部范围中。 – 2011-02-28 22:54:54

+0

@Matt:但要做到这一点,并且还要调用'each',我仍然需要至少暂时存储集合本身。为什么*不*这样做? – 2011-02-28 22:57:14

+1

是的,唯一的解决方案。我一直认为jQuery应该提供集合作为回调的额外参数。 – lonesomeday 2011-02-28 22:58:04

1

你的意思是像lengthsize()

参考文献:http://api.jquery.com/length/

+1

我想,他的意思是在**循环内**。 – 2011-02-28 22:51:34

+1

长度是属性,而不是函数。 size()是返回长度的函数。 – Orbit 2011-02-28 22:51:42

+0

@Matt“循环时”。不过,我不确定这种功能会有很多实际用途。 – 2011-02-28 22:54:28

3

使用.length财产。它是而不是的一个功能。

alert($('.class').length); // alerts a nonnegative number 
+0

谢谢,我纠正了我的上面,以反映.length是一个属性。 – kojiro 2011-02-28 22:54:10

3

如果您正在使用一个版本的jQuery小于1.8,你可以使用$版本('.class')。size(),它取零参数。有关.size()方法的更多信息,请参见documentation

但是,如果您正在使用(或计划升级)到1.8或更高版本,则可以使用$('。class')。length属性。有关.length属性的更多信息,请参见documentation