原文:http://www.frontopen.com/1394.html
在jquery中,遍历对象和数组,经常会用到$().each和$.each(),两个方法。
$().each 在dom处理上面用的较多。如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,例如:
$(“input[name=’ch’]”).each(function(i){
if($(this).attr(‘checked’)==true)
{
//一些操作代码
}
回调函数是可以传递参数,i就为遍历的索引。
遍历一个数组通常用$.each()来处理 例如:
$.each([{name:"limeng",email:"xfjylimeng"},{name:"hehe",email:"xfjylimeng"}],function(i,n)
{
alert("索引:"+i+"对应值为:"+n.name);
});
参数i为遍历索引值,n为当前的遍历对象.
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
输出:one two three four five
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){
alert(item[0]);
});
输出:1 4 7
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) {
alert(obj[key]);
});
输出:1 2 3 4 5
下面提一下jQuery的each方法的几种常用的用法
Js代码
var arr = [ “one”, “two”, “three”, “four”];
$.each(arr, function(){
alert(this);
});
//上面这个each输出的结果分别为:one,two,three,four
var arr1 = [[1, 4, 3], [4, 6, 6], [7, 20, 9]]
$.each(arr1, function(i, item){
alert(item[0]);
});
//其实arr1为一个二维数组,item相当于取每一个一维数组,
//item[0]相对于取每一个一维数组里的第一个值
//所以上面这个each输出分别为:1 4 7
var obj = { one:1, two:2, three:3, four:4};
$.each(obj, function(key, val) {
alert(obj[key]);
});
//这个each就有更厉害了,能循环每一个属性
//输出结果为:1 2 3 4