jQuery each用法及each解析json


<body>
<button>Click Here</button>
<div>this is a div</div>
<p>this is a p</p>
<span>this is a span</span><br /><br />
<b>this is a b</b><br /><br />
<em>this is a em</em>
</body>
$(function(){
    $("button").click(
    function()
{
    var a1="";
    var a2="";
    var a3="";
    var a4="";
    var a5="";
    var colors=['red','blue','green','yellow','black','white','orange'];
    var color_ary=[{'id':'red','code':'01'},{'id':'blue','code':'02'},{'id':'green','code':'03'},{'id':'yellow','code':'04'},
             {'id':'black','code':'05'},{'id':'white','code':'06'},{'id':'orange','code':'07'}];

  $.each(colors,function(item){a1+=item+",";});
  //each方法中的函數參數為一個時,此參數為遍歷的索引值,同for循環的 i 變量。
  $.each(colors,function(index,item){a2+=item[index]+",";});
  //each方法中的函數參數為兩個時,item為數組的每一項,item[index]返回的是對item對象的提取。
  $.each(colors,function(index,item){a3+=item+",";});
  //item為數組的每一項,如此可正常的顯示數組,同樣的color[index]也可正常的顯示數組。
  $.each(color_ary,function(index,item){a4+=item.id+":"+item.code+",";});
  //當數據為json格式時,可以如此來解析此json
  $.each(color_ary,function(index,item){a5+=color_ary[index].id+":"+color_ary[index].code+",";});
  //當數據為json格式時,也可以如此來解析此json

  $("div").text(a1);
  $("p").text(a2);
  $("span").text(a3);
  $("b").text(a4);
  $("em").text(a5)
      })
})

 

輸出結果:


免責聲明!

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



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