最近一直在研究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))函數。