jquery的$(selector).each(function(index,element))和$.each(dataresource,function(index,element))的区别

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

定义和用法

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

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

参数 描述
function(index,element)

必需。为每一个匹配元素规定运行的函数。json

  • index - 选择器的 index 位置
  • element - 当前的元素(也可以使用 "this" 选择器)

做用:在dom方面用的较多app

 

示例dom

 

html部分文档函数

 

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

 

js遍历函数:spa

 

    $("li").each(function(){
      alert($(this).text())
    });.net

 

效果3d

 

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

做用:在数据处理上用的比较多

示例:

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

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

 

输出结果:

最终结论:

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

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

 

参考自:http://www.w3school.com.cn/jquery/traversing_each.asp

https://blog.csdn.net/gao_xu_520/article/details/78588977

相关文章
相关标签/搜索