JQuery中的$().each 以及 $.each的区别

最近一直在研究JS,今天看到遍历模块的时候,看到了这个函数:html

$(selector).each(function(index,element))前端

可是想一想,这个函数和以前项目里面用到的遍历数据的函数不是同一个呀(项目里面用到的函数:$.each(dataresource,function(index,element))),因而,就好好研究了下,果真在JS里面有两个类似的函数,因而也就有了今天的主题:json

1
1.$(selector).each(function(index,element))

  

1
2.$.each(dataresource,function(index,element))

  接下来就对这两个函数作深刻的探讨:app

 

1.$(selector).each(function(index,element))dom

做用:在dom处理上面用的较多函数

示例:post

html部分文档学习

<ul id="each_id">
<li>Coffee</li>
<li>Soda</li>
<li>Milk</li>
</ul>this

 

js遍历函数:spa

function traversalDOM(){
$("#each_id li").each(function(){
      alert($(this).text())
    });
}

输出结果:

2.$.each(dataresource,function(index,element))

 

做用:在数据处理上用的比较多,主要仍是用来处理后台传到前端的数据的 

示例:

此处没有html代码,只有js代码,以下:

function traversalData(){
var jsonResourceList = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"}]';
if(jsonResourceList.length >0){
$.each(JSON.parse(jsonResourceList), function(index, obj) {
    alert(obj.tagName);
});
}
}

输出结果:

3.最终结论:

在遍历DOM时,一般用$(selector).each(function(index,element))函数;

在遍历数据时,一般用$.each(dataresource,function(index,element))函数。

用心努力学习才会有收获 既然选择远方,便只顾风雨兼程
相关文章
相关标签/搜索