2011-02-28 53 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