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)
      })
})

 

输出结果:

posted @ 2012-03-29 11:31  纯属偶然_黄勇  阅读(16724)  评论(0编辑  收藏  举报