官方說明:
jQuery.each(object, [callback])
概述
通用例遍方法,可用於例遍對象和數組。
不同於例遍 jQuery 對象的 $().each() 方法,此方法可用於例遍任何對象。回調函數擁有兩個參數:第一個為對象的成員或數組的索引,第二個為對應變量或內容。如果需要退出 each 循環可使回調函數返回 false,其它返回值將被忽略。
參數
objectObject
需要例遍的對象或數組。
callback (可選)Function
每個成員/元素執行的回調函數。
each,一般用來循環 數組、對象、Dom元素
1.循環數組
a.一維數組
var arr = [ "one", "two", "three", "four"]; $.each(arr, function(){ alert(this); });
//arr為循環對象,上面這個each輸出的結果分別為:one,two,three,four
還可以寫成:
$.each(arr, function(i,v){ // console.log(arr[i]); // one ,two ... // console.log(this) //類型為字符串對象
console.log(v) //one ,two ...
});
b.二維數組
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); });
item相當於取每一個一維數組,
item[0]相對於取每一個一維數組里的第一個值,所以上面這個each輸出分別為:1 4 7
2.循環對象
var obj = { one:1, two:2, three:3, four:4}; $.each(obj, function(i) { alert(obj[i]); });
循環每一個屬性,輸出結果為:1 2 3 4
3.循環Dom
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("li").each(function(){ alert($(this).text()) }); }); }); </script> </head> <body> <button>輸出每個列表項的值</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> </body> </html>
