jQuery.each()
jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object
Description: 一個通用的迭代函數(shù),它可以用來無縫迭代對象和數(shù)組。數(shù)組和類似數(shù)組的對象通過一個長度屬性(如一個函數(shù)的參數(shù)對象)來迭代數(shù)字索引,從0到length - 1。其他對象迭代通過其命名屬性。
-
version added: 1.0jQuery.each( collection, callback(indexInArray, valueOfElement) )
collection遍歷的對象或數(shù)組。
callback(indexInArray, valueOfElement)每個成員/元素執(zhí)行的回調(diào)函數(shù)。
$.each()函數(shù)和.each()是不一樣的,這個是專門用來遍歷一個jQuery對象。$.each()函數(shù)可用于迭代任何集合,無論是“名/值”對象(JavaScript對象)或陣列。在一個數(shù)組的情況下,回調(diào)函數(shù)每次傳遞一個數(shù)組索引和相應(yīng)的數(shù)組值。(該值也可以通過訪問this關(guān)鍵字,但是JavaScript將始終包裹this值作為一個Object ,即使它是一個簡單的字符串或數(shù)字值。)該方法返回其第一個參數(shù),這是迭代的對象。
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
這將產(chǎn)生兩個信息:
0: 52
1: 97
如果對象是作為集合使用,回調(diào)函數(shù)每次傳遞一個鍵值對的:
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
再次,這將產(chǎn)生兩個信息:
flammable: inflammable
duh: no duh
我們可以打破$.each()返回使得回調(diào)函數(shù)在某一特定的迭代循環(huán)的false 。返回non-false是一樣的一個continue在一個循環(huán)語句,它會立即跳轉(zhuǎn)到下一個迭代。
Examples:
Example: Iterates through the array displaying each number as both a word and numeral
<!DOCTYPE html>
<html>
<head>
<style>
div { color:blue; }
div#five { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<div id="five"></div>
<script>
var arr = [ "one", "two", "three", "four", "five" ];
var obj = { one:1, two:2, three:3, four:4, five:5 };
jQuery.each(arr, function() {
$("#" + this).text("Mine is " + this + ".");
return (this != "three"); // will stop running after "three"
});
jQuery.each(obj, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
</script>
</body>
</html>
Demo:
Example: Iterates over items in an array, accessing both the current item and its index.
$.each( ['a','b','c'], function(i, l){
alert( "Index #" + i + ": " + l );
});
Example: Iterates over the properties in an object, accessing both the current item and its key.
$.each( { name: "John", lang: "JS" }, function(k, v){
alert( "Key: " + k + ", Value: " + v );
});