天天看点

jquery的$().each,$.each的区别与详解

[b]jquery的$().each,$.each的区别与详解[/b]

[b]$().each[/b]

对匹配上的每个DOM对象调用一个处理(函数)

$().each,对于这个方法,在dom处理上面用的较多

如:

$(“input[name=’ch’]”).each(function(i){
if($(this).attr(‘checked’)==true)
{
//一些操作代码

}
           

[b]$.each()[/b]

用于遍历一个对象

[b]遍历一个数组[/b]

$.each([{“name”:”limeng”,”email”:”xfjylimeng”},{“name”:”hehe”,”email”:”xfjylimeng”},function(i,n)
{
    alert(“索引:”+i,”对应值为:”+n.name);
});
           

参数i为遍历索引值,n为当前的遍历对象(数组里的一个子项).

也可以用i作为下标进行访问

var arr1 = [ “one”, “two”, “three”, “four”, “five” ];
$.each(arr1, function(){
	alert(this);
});
           

遍历每一个数组项:

输出:one two three four five

var arr1 = ["one", "two", "three", "four", "five"];
$.each(arr1, function (i,n) {
	alert(i);
	alert(arr1[i]);
});
           

遍历每一个数组项:

输出:one two three four five

i为遍历索引值

n为数组项

var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
	alert(item[0]);
});
           

i为遍历索引值

item为二维数组里的一个子项(一维数组)

输出:1 4 7

var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
	alert(obj[key]);
});
           

key为对象里(key/value)里的key

val为对象里(key/value)里的value

参考原文:[url]http://www.frontopen.com/1394.html[/url]

继续阅读