jQuery.each()
jQuery.each( collection, callback(indexInArray, valueOfElement) ) Returns: Object
Description: 一個(gè)通用的迭代函數(shù),它可以用來(lái)無(wú)縫迭代對(duì)象和數(shù)組。數(shù)組和類似數(shù)組的對(duì)象通過一個(gè)長(zhǎng)度屬性(如一個(gè)函數(shù)的參數(shù)對(duì)象)來(lái)迭代數(shù)字索引,從0到length - 1。其他對(duì)象迭代通過其命名屬性。
-
version added: 1.0jQuery.each( collection, callback(indexInArray, valueOfElement) )
collection遍歷的對(duì)象或數(shù)組。
callback(indexInArray, valueOfElement)每個(gè)成員/元素執(zhí)行的回調(diào)函數(shù)。
$.each()函數(shù)和.each()是不一樣的,這個(gè)是專門用來(lái)遍歷一個(gè)jQuery對(duì)象。$.each()函數(shù)可用于迭代任何集合,無(wú)論是“名/值”對(duì)象(JavaScript對(duì)象)或陣列。在一個(gè)數(shù)組的情況下,回調(diào)函數(shù)每次傳遞一個(gè)數(shù)組索引和相應(yīng)的數(shù)組值。(該值也可以通過訪問this關(guān)鍵字,但是JavaScript將始終包裹this值作為一個(gè)Object ,即使它是一個(gè)簡(jiǎn)單的字符串或數(shù)字值。)該方法返回其第一個(gè)參數(shù),這是迭代的對(duì)象。
$.each([52, 97], function(index, value) {
alert(index + ': ' + value);
});
這將產(chǎn)生兩個(gè)信息:
0: 52
1: 97
如果對(duì)象是作為集合使用,回調(diào)函數(shù)每次傳遞一個(gè)鍵值對(duì)的:
var map = {
'flammable': 'inflammable',
'duh': 'no duh'
};
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
再次,這將產(chǎn)生兩個(gè)信息:
flammable: inflammable
duh: no duh
我們可以打破$.each()返回使得回調(diào)函數(shù)在某一特定的迭代循環(huán)的false 。返回non-false是一樣的一個(gè)continue在一個(gè)循環(huán)語(yǔ)句,它會(huì)立即跳轉(zhuǎn)到下一個(gè)迭代。
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 );
});