您的位置:首页 > Web前端 > JQuery

Jquery中each的三种遍历方法

2017-11-14 10:33 786 查看
1、选择器+遍历

$('div').each(function (i){
i就是索引值
this 表示获取遍历每一个dom对象
});


2、选择器+遍历

$('div').each(function (index,domEle){
index就是索引值
domEle 表示获取遍历每一个dom对象
});


3、更适用的遍历方法

1)先获取某个集合对象

2)遍历集合对象的每一个元素

var d=$("div");
$.each(d,function (index,domEle){
d是要遍历的集合
index就是索引值
domEle 表示获取遍历每一个dom对
});


在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方法,用起来非常的爽,不用再像原来那样写for循环,jQuery源码里自己也有很多用到each方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: