jQuery中$.each()方法的使用

$.each()是對數組,json和dom結構等的遍歷,說一下他的使用方法吧。json

一、遍歷一維數組數組

var arr1=['aa','bb','cc','dd'];
 $.each(arr1,function(i,val){ //兩個參數,第一個參數表示遍歷的數組的下標,第二個參數表示下標對應的值
 console.log(i+'```````'+val);

輸出的結果爲:dom

0```````aa
1```````bb
 2```````cc
3```````dd

二、遍歷二維數組對象

var arr2=[['aaa','bbb'],['ccc','ddd'],['eee','fff']];
$.each(arr2,function(i,item){ //兩個參數,第一個參數表示下標,第二個參數表示一維數組中的每個數組
 console.log(i+'````'+item);

輸出的結果爲:索引

0````aaa,bbb
1````ccc,ddd
2````eee,fff

此時能夠對輸出的一維數組進行遍歷input

$.each(item,function(i,val){  //遍歷二維數組
          console.log(i+'`````'+val);
  })

輸出的結果爲:it

0````aaa,bbb
    0`````aaa
    1`````bbb
1````ccc,ddd
    0`````ccc
    1`````ddd
2````eee,fff
    0`````eee
    1`````fff

三、處理jsonio

var json1={key1:'a',key2:'b',key3:'c'};
 $.each(json1,function(key,value){  //遍歷鍵值對
            console.log(key+'````'+value);
  })

輸出的結果爲:console

key1````a
key2````b
key3````c

四、當二位數組中有json對象時function

複製代碼

var arr3=[{name:'n1',age:18},{name:'n2',age:20},{name:'n3',age:22}];
        $.each(arr3,function(i,val){
            console.log(i+'`````'+val);   
    //輸出
    /* 0`````[object Object] 1`````[object Object] i2`````[object Object]*/
            console.log(val.name); //獲取每個json裏面的name值
            console.log(val["name"]);
            $.each(val,function(key,val2){
                console.log(key+'```'+val2);
            })
        });

複製代碼

五、處理dom元素

<input name="aaa" type="hidden" value="111" />
<input name="bbb" type="hidden" value="222" />
<input name="ccc" type="hidden" value="333" />
<input name="ddd" type="hidden" value="444"/>

複製代碼

$.each($('input:hidden'),function(i,val){
            console.log(i+'````'+val);
            /*0````[object HTMLInputElement]
            1````[object HTMLInputElement]
            2````[object HTMLInputElement]
            3````[object HTMLInputElement]*/
            console.log(val.name+'`````'+val.value);
           /* aaa`````111
           bbb`````222
            ccc`````333
           ddd`````444*/
        })

複製代碼

以上就是$.each()最基本的使用了,

jQuery中還有另一種寫法來遍歷元素

$("input:hidden").each(function(i,val){  //第一個參數表示索引下標,第二個參數表示當前索引元素
    alert(i);
    alert(val.name);
    alert(val.value);       
});
相關文章
相關標籤/搜索