在jquery循環遍歷一般有兩種.一種是for,這里不舉例,另一種是each.這里主要是說明each的循環遍歷的用法
一般格式
$.each(XXX,function(XXX){ //code }); $(XXX).each(function(XXX){ //code });
XXX具體代表什么根據需要遍歷的值的類型來定.
1.$().each 在dom處理上面用的較多。如果頁面有多個input標簽類型為checkbox,對於這時用$().each來處理多個checkbook,例如:
$("input[name=’check’]").each(function(i){ //i代表下標 if($(this).attr('checked')==true) { //code }
2.$.each()來循環遍歷一個數組,或者對象
2.$.each()來循環遍歷一個數組,或者對象.例如:
var arrayTest = [[1,2,3],[4,5,6],[7,8,9]];
$.each(arrayTest,function(n,item){ //n代表當前循環的次數,item為當前循環的對象
alert(item[n]);//1;5;9 alert(arrayTest[n]);//1,2,3;4,5,6;7,8,9 alert(item);//1,2,3;4,5,6;7,8,9 $.each(item,function(){ //將第一次循環的對象再次循環,就實現了二維數據的遍歷,如果有2以上的數組,則同理循環多次 alert(this);//1;2;3;4;5;6;7;8;9 this代表當前元素 }); }); var obj = {one:1,tow:2,three:3,four:4}; $.each(obj,function(key,value){ alert(key);//one;tow;three;four alert(obj[key]);//1;2;3;4 alert(value)////1;2;3;4 });