jquery的$().each,$.each的区别

each() 方法规定为每个匹配元素规定运行的函数。

提示:返回 false 可用于及早停止循环。

语法

$(selector).each(function(index,element))
 参数                                       描述
function(index,element)             必需。为每个匹配元素规定运行的函数。
                                    index - 选择器的 index 位置
                                    element - 当前的元素(也可使用 "this" 选择器)

 在jquery中,遍历对象和数组,经常会用到$().each$.each(),两个方法。两个方法是有区别的,从而这两个方法在针对不同的操作上,显示了各自的特点。

 $().each,对于这个方法,在dom处理上面用的较多。如果页面有多个input标签类型为checkbox,对于这时用$().each来处理多个checkbook,

  栗子①

$("input[name='ch']").each(function(i){
  if($(this).attr('checked')==true)
  {
    //一些操作代码
  }
}

回调函数是可以传递参数,i就为遍历的索引。

------------------------------------------------------------------------------------------------

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

参数i为遍历索引值,n为当前的遍历对象.

var arr=[1,2,3,4,5,6];
$.each(arr, function() {
    alert(this);
});

输出1,2,3,4,5,6

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

输出1,4,7

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

输出1,2,3

在jQuery里有一个each方法,不用再像原来那样写for循环。

 

摘自:http://www.frontopen.com/1394.html

 

posted @ 2016-08-21 12:09  晴晴加油  阅读(446)  评论(0编辑  收藏  举报