原文出處https://www.cnblogs.com/tylerdonet/archive/2013/04/05/3000618.htmljavascript
jQuery 遍歷函數包括了用於篩選、查找和串聯元素的方法html
var arr=[1,2,3,4];
$.each(arr,function(){
alert(this)
})//1,2,3,4java
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]] $.each(arr1, function(i, item){ alert(item[0]); }); //其實arr1爲一個二維數組,item至關於取每個一維數組, //item[0]相對於取每個一維數組裏的第一個值 //因此上面這個each輸出分別爲:1 4 7
var obj = { one:1, two:2, three:3, four:4}; $.each(obj, function(i) { alert(obj[i]); }); //這個each就有更厲害了,能循環每個屬性 //輸出結果爲:1 2 3 4
2.遍歷DOM元素jquery
<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>
3.each和map的比較數組
each方法:函數
定義一個空數組,經過each方法,往數組添加ID值;最後將數組轉換成字符串後,alert這個值;this
$(function(){ var arr = []; $(":checkbox").each(function(index){ arr.push(this.id); }); var str = arr.join(","); alert(str); })
$(function(){ var str = $(":checkbox").map(function() { return this.id; }).get().join(); alert(str); })