$.each() is a traversal of arrays, json and dom structures, etc. Let me tell you how to use it.
1. Traverse a one-dimensional array
var arr1=['aa','bb','cc','dd']; $.each(arr1,function(i,val){ //Two parameters, the first parameter represents the subscript of the traversed array, and the second parameter represents the value corresponding to the subscript console.log(i+'```````'+val);
The output is:
0```````aa 1```````bb 2```````cc 3```````dd
2. Traverse a two-dimensional array
var arr2=[['aaa','bbb'],['ccc','ddd'],['eee','fff']]; $.each(arr2,function(i,item){ //Two parameters, the first parameter represents the subscript, and the second parameter represents each array in the one-dimensional array console.log(i+'````'+item);
The output is:
0````aaa,bbb 1````ccc,ddd 2````eee,fff
At this point, the output one-dimensional array can be traversed
$.each(item,function(i,val){ //traverse the two-dimensional array console.log(i+'`````'+val); })
The output is:
0````aaa,bbb 0`````aaa 1`````bbb 1````ccc,ddd 0`````ccc 1`````ddd 2````eee,fff 0`````eee 1`````fff
3. Processing json
var json1={key1:'a',key2:'b',key3:'c'}; $.each(json1,function(key,value){ //traverse key-value pairs console.log(key+'````'+value); })
The output is:
key1````a key2````b key3````c
4. When there are json objects in the two-digit array
var arr3=[{name:'n1',age:18},{name:'n2',age:20},{name:'n3',age:22}]; $.each(arr3,function(i,val){ console.log(i+'`````'+val); // output /* 0`````[object Object] 1`````[object Object] i2`````[object Object]*/ console.log(val.name); //Get the name value in each json console.log(val["name"]); $.each(val,function(key,val2){ console.log(key+'```'+val2); }) });
5. Handling DOM elements
<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*/ })
The above is the most basic use of $.each(),
There is another way to traverse elements in jQuery
$("input:hidden").each(function(i,val){ //The first parameter represents the index subscript, and the second parameter represents the current index element alert(i); alert(val.name); alert(val.value); });