$.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>