2011-05-06 78 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