在jquery中,遍歷對象和數組,經常會用到$().each和$.each(),兩個方法。
$().each:
對於這個方法,在dom處理上面用的較多。如果頁面有多個input標簽類型為checkbox,對於這時用$().each來處理多個checkbook,例如:
$(“input[name=’ch’]”).each(function(i){ if($(this).attr(‘checked’)==true) { //一些操作代碼 } )}
$(this)代表當前遍歷的對象,i就為遍歷的索引。
$.each():
對於遍歷一個數組,用$.each()來處理,例如:
var arr1 = [ “one”, “two”, “three”, “four”, “five” ]; $.each(arr1, function(){ alert(this); }); 輸出:one two three four five
$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,item) { alert(“索引:”+i,”對應值為:”+item.name); });
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] $.each(arr2, function(i, item){ alert(item[0]); }); 輸出:1 4 7
item代表當前的遍歷的對象,i為遍歷的索引。