我试图从JSON对象中检索内容并将其显示在页面上。我能够检索对象并遍历,以提取各种内容并显示div中的块。目标是显示图像头像,名字和姓氏。通过下面的代码,我可以显示名字和姓氏,但图像始终显示为每个图像列表中的最后一幅图像。我如何获取URL并将其附加到我在每个div中创建的图像?使用jQuery从json对象附加图像src
$(document).ready(function() {
$.getJSON('http://www.url.com/?callback=?', function(data) {
$.each(data, function(index, entry) {
var html = '<div class="entry">';
html += '<img/>';
var createImageURL = function() {
var thisImg = entry.AvatarUrl;
var thisPic = $('.entry img');
$(thisPic).attr('src',thisImg);
}
createImageURL();
html += '<h3 class="first-name">' + entry.FirstName + '</h3>';
html += '<div class="last-name">' + entry.LastName + '</div>';
html += '</div>';
$('#dictionary').append(html);
});
});
});
这里是JSON数据的一个示例:
{
"AvatarUrl":"http://www.gravatar.com/avatar/35b2d5391e4a766e57d0d1f4a767f61f?s=120&d=retro",
"Id":4,
"FirstName":"Aimee",
"LastName":"Lacariere",
"Location":"Seattle, Washington"
}
。以下来自Woodszy的回应似乎以一种很好的方式解决了这个问题。谢谢。 – Dave 2011-05-06 21:43:19