$.each()可以實現對數組,json和DOM結構等的遍歷。
定義:以每一個匹配的元素作爲上下文來執行一個函數。
注意點:$.each()中的 this 指的是DOM元素,而不是jQuery 對象,如果要獲取jQuery 對象,需要使用 $(this) 。
下面我們來看看它的應用方法:
1.遍歷一維數組
var arr_1 = ['a','b','c'];
$.each(arr_1,function(index,value){ //其中index是指數組的下標,value指相對應的值;
console.log(index +" : " + value + "<br>");
})
輸出:
0 : a
1 : b
2 : c
2.遍歷二維數組
var arr_1 = [
['a','b'],
['c','d'],
['e','f']
];
$.each(arr_1,function(index,item){ //其中index是指數組的下標,item指相對應的數組;
console.log(index +" : " + item);
})
輸出:
0 : a,b
1 : c,d
2 : e,f
注:可以對遍歷之後的每個數組再進行遍歷。
3.處理JSON
var json_1 = {"name":"jim","age":"28"};
$.each(json_1,function(key,value){ //其中key是json的key,value指相對應的值;
console.log(key +" : " + value);
})
輸出:
name : jim
age : 28
4.處理DOM
<input name="a" type="hidden" value="1" />
<input name="b" type="hidden" value="2" />
<input name="c" type="hidden" value="3" />
<script>
$.each($('input:hidden'),function(index,value){
console.log(index+ ' : ' +value);
/*
0 : [object HTMLInputElement]
1 : [object HTMLInputElement]
2 : [object HTMLInputElement]
*/
console.log(value.name+' : '+value.value);
/*
a : 1
b : 2
c : 3
*/
})
</script>
6.還可以這樣來使用:
<img/><img/>
<script>
$("img").each(function(i){
this.src = "test" + i + ".jpg";
});
</script>
結果:
<img src="test0.jpg" />, <img src="test1.jpg" />
注意:你可以使用 'return' 來提前跳出 each() 循環。
<button>點擊改變顏色</button>
<span></span>
<div>0</div>
<div>1</div>
<div>2</div>
<div>3</div>
<div id="stop">4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<script>
$("button").click(function () {
$("div").each(function (index, item) {
// item == this
$(item).css("backgroundColor", "red");
if ($(this).is("#stop")) {
$("span").text("執行到第 :" + index + "行");
return false;
}
});
});
</script>