最近一直在研究JS,今天看到遍歷模塊的時候,看到了這個函數:
$(selector).each(function(index,element))
但是想想,這個函數和之前項目里面用到的遍歷數據的函數不是同一個呀(項目里面用到的函數:$.each(dataresource,function(index,element))),於是,就好好研究了下,果然在JS里面有兩個相似的函數,於是也就有了今天的主題:
1.$(selector).each(function(index,element))
2.$.each(dataresource,function(index,element))
接下來就對這兩個函數做深入的探討:
1.$(selector).each(function(index,element))
作用:在dom處理上面用的較多
示例:
html部分文檔
<ul id="each_id">
<li>Coffee</li>
<li>Soda</li>
<li>Milk</li>
</ul>
js遍歷函數:
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))函數。
