http://www.cnblogs.com/shaohz2014/p/3638848.html
在jquery中,遍歷對象和數組,經常會用到$().each和$.each(),兩個方法。兩個方法是有區別的,從而這兩個方法在針對不同的操作上,顯示了各自的特點。
$().each,對於這個方法,在dom處理上面用的較多。如果頁面有多個input標籤類型爲checkbox,對於這時用$().each來處理多個checkbook,例如:
$("input[name='ch']").each(function(i){
if($(this).attr('checked')==true) {
//一些操作代碼
}
回調函數是可以傳遞參數,i就爲遍歷的索引。
對於遍歷一個數組,用$.each()來處理,簡直爽到了極點。例如:
$.each([{"name":"limeng","email":"xfjylimeng"},{"name":"hehe","email":"xfjylimeng"}],function(i,n) {
alert(“索引:"+i,"對應值爲:"+n.name);
});
參數i爲遍歷索引值,n爲當前的遍歷對象.
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
輸出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
$.each(arr2, function(i, item){
alert(item[0]);
});
輸出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
輸出:1 2 3 4 5
生活不止眼前的苟且,還有詩和遠方。。。