2011-05-06 77 views
0

我试图从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" 
} 

回答

1

首先这段代码:

var thisPic = $('.entry img'); 

将返回所有在每个所创建的IMGS的阵列()循环。也许你打算让第一个div独特的类价值?

但实际上你不应该需要调用一个函数来设置一个属性。只需将它添加到直接的字符串:

var html = '<div class="entry">'; 
html += '<img src="' + entry.AvatarUrl + '" alt="avatar" />'; 
html += '<h3 class="first-name">' + entry.FirstName + '</h3>'; 
html += '<div class="last-name">' + entry.LastName + '</div>'; 
html += '</div>'; 
0

你应该做的是这样的:

$(document).ready(function() { 
    $.getJSON('http://www.url.com/?callback=?', function(data) { 
     $.each(data, function(index, entry) { 
      $html = $('<div class="entry" />'); 
      $html.append('<img/>'); 
      var createImageURL = function() { 
       var thisImg = entry.AvatarUrl; 
       var thisPic = $('.entry img', $html); //This was your most conflicting line 
       $(thisPic).attr('src',thisImg); 
      } 
      createImageURL(); 
      $html.append('<h3 class="first-name">' + entry.FirstName + '</h3>'); 
      $html.append('<div class="last-name">' + entry.LastName + '</div>'); 

      $('#dictionary').append($html); 
     }); 
    }); 
}); 

正如你所看到的,我们使用append而不是串联。您的错误发生在var thisPic = $('.entry img');选择器中,导致它将搜索所有文档。白衣这样的:

$('.entry img', $html); 

我们只选择内刚刚创建的HTML图像
希望这会有所帮助。干杯

+0

。以下来自Woodszy的回应似乎以一种很好的方式解决了这个问题。谢谢。 – Dave 2011-05-06 21:43:19

0

我认为问题是你正在创建类的条目的多个div然后重新分配img src到div每次循环你的代码。而不是调用createurl功能加入这一行:

html += '<img src="' + entry.AvatarUrl + '"/>'; 

,并删除不出现工作中的作用

+0

谢谢,完美的作品。我意识到我的目标是一个div类,它会重新发生,但我无法解决如何将AvatarUrl对象直接添加到src .attr。再次感谢。 – Dave 2011-05-06 21:41:19