當使用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. 並行選項.each()jquery
- 4. jQuery有多少th hasClass
- 5. 確定有多少行,每行有多少個項目
- 6. Jquery。 .each()
- 7. xlst for each - add class to 1st,4th,7th,10th,...項目
- 8. DBIx :: Class :: Row :: set_columns能做多少魔法?
- 9. Sass @each有多個變量
- 10. 如何使用jquery $ .each打開多個選項卡
- 11. jQuery each-Method追加項目兩次
- 12. jQuery,使用.each()提交多個表單()使用.each()
- 13. tbody。 each();方法缺少watir
- 14. jQuery .each()獲取多個div的值
- 15. 在jquery的$ .each()
- 16. each()jquery問題
- 17. jquery .each array json
- 18. Jquery each toggleClass
- 19. jQuery .each()索引?
- 20. jQuery each()怪異
- 21. jquery .each()loop
- 22. jQuery - setInterval與$ .each
- 23. jQuery each()限制
- 24. .each()on JQuery Dropdown
- 25. jQuery .each()和CodeMirror
- 26. jQuery Promise each loop
- 27. jQuery $ .Deferreds和$ .each
- 28. 從jquery $ .each
- 29. jquery - each和data()
- 30. jQuery each和keyup
或者,將'length'值本身存儲在外部範圍中。 – 2011-02-28 22:54:54
@Matt:但要做到這一點,並且還要調用'each',我仍然需要至少暫時存儲集合本身。爲什麼*不*這樣做? – 2011-02-28 22:57:14
是的,唯一的解決方案。我一直認爲jQuery應該提供集合作爲回調的額外參數。 – lonesomeday 2011-02-28 22:58:04