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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM