ITeye博客

JQuery遍历JSON

sty2008boy · 2011-12-01 17:14 · JQuery · JavaScript · Web前端 · json · each · Markdown

这里来使用each方法来遍历json对象的数据
代码

varcomments=[
{
"username":"张三",
"content":"沙发."
},
{
"username":"李四",
"content":"板凳."
},
{
"username":"王五",
"content":"地板."
}
];


varhtml='';
$.each( comments ,function(commentIndex, comment) {
html+='<div class="comment"><h6>'+comment['username']+':</h6><p class="para">'+comment['content']+'</p></div>';
})


$('#resText').html(html);
说明: each在每次执行函数时,都会给函数传递一个表示作为执行环境的元素在匹配的元素集合中所处位置的数字值作为参数。这里所指的

则为commentIndex, 而每一个commentIndex所对应的值则为comment, comment则为其中一个json对象,即如
{
"username":"张三",
"content":"沙发."
}





又如如下的方式,使用 点访问符的方式来进行访问


代码


$('#send').click(function() {
$.ajax({
type:"GET",
url:"http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",
dataType:"jsonp",
success :function(data){
$.each(data.items,function( i,item ){
$("<img class='para'/>").attr("src", item.media.m ).appendTo("#resText");
if( i==3) {
returnfalse;
}
});
}
});
});


评论(1)

  1. #1 楼 · 天使建站 · 2018-06-16 15:48

    :( :( :( :( :( 只有代码,不能测试,太不方便,还是结合这里的一起看吧,里面有具体的实例,还有在线实例演示: jquery解析遍历json的方法和实例

    文件链接地址: http://www.aijquery.cn/Html/jqueryrumen/98.html :lol: :lol: :lol: :lol: :lol:

评论功能维护中,当前仅展示历史评论。