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

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

定义和用法

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

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

参数描述
function(index,element)

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

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

作用:在dom方面用的较多

示例

html部分文档

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

js遍历函数:

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

效果

 $.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

原文地址:https://www.cnblogs.com/YangBinChina/p/10280623.html