当使用jQuery选择器循环一组项目时,有一种方法可以找出集合上有多少项目?
回答
如果您使用链式语法:
$(".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
});
你的意思是像length
或size()
?
我想,他的意思是在**循环内**。 – 2011-02-28 22:51:34
长度是属性,而不是函数。 size()是返回长度的函数。 – Orbit 2011-02-28 22:51:42
@Matt“循环时”。不过,我不确定这种功能会有很多实际用途。 – 2011-02-28 22:54:28
使用.length
财产。它是而不是的一个功能。
alert($('.class').length); // alerts a nonnegative number
谢谢,我纠正了我的上面,以反映.length是一个属性。 – kojiro 2011-02-28 22:54:10
如果您正在使用一个版本的jQuery小于1.8,你可以使用$版本('.class')。size(),它取零参数。有关.size()方法的更多信息,请参见documentation。
但是,如果您正在使用(或计划升级)到1.8或更高版本,则可以使用$('。class')。length属性。有关.length属性的更多信息,请参见documentation。
- 1. 有多少(generic?)class wordpress?
- 2. “ng-class”on each clicked item
- 3. jQuery有多少th hasClass
- 4. 确定有多少行,每行有多少个项目
- 5. DBIx :: Class :: Row :: set_columns能做多少魔法?
- 6. 如何使用jquery $ .each打开多个选项卡
- 7. tbody。 each();方法缺少watir
- 8. jQuery .each()AJAX
- 9. jQuery .each()和CodeMirror
- 10. 从jquery $ .each
- 11. jQuery .each()索引?
- 12. jquery - each和data()
- 13. jQuery $ .Deferreds和$ .each
- 14. .each()on JQuery Dropdown
- 15. Jquery each toggleClass
- 16. 共享首选项有多少数据?
- 17. django-notification:有多少观察项目
- 18. Firebase Spark版本中有多少项目?
- 19. 如果select中的选项有class然后添加class
- 20. 多少有些失落与jQuery + PHP + JSON
- 21. jQuery .each()重复所有行的答案
- 22. .each()迭代后,Jquery DOM没有更新
- 23. jQuery $ .each循环没有执行
- 24. jquery each()计数器
- 25. jquery if then each arrays
- 26. javascript jquery .each()问题
- 27. jQuery each()和“on success”?
- 28. jQuery .each()this和element
- 29. jQuery .each()未运行
- 30. jQuery each()打破null
或者,将'length'值本身存储在外部范围中。 – 2011-02-28 22:54:54
@Matt:但要做到这一点,并且还要调用'each',我仍然需要至少暂时存储集合本身。为什么*不*这样做? – 2011-02-28 22:57:14
是的,唯一的解决方案。我一直认为jQuery应该提供集合作为回调的额外参数。 – lonesomeday 2011-02-28 22:58:04