Attaching image src from a json object using jQuery
I am trying to retrieve content from a JSON object and display it on a page. I am able to retrieve the object and iterate through to pull out various content and display the in blocks of divs. The goal is to display the image avatar, the first name and the last name. With the below code I can display the first and last name, but the image always shows up as the last image in the list for every image. How can I grab the URL and append it to the image that I am creating in each div?
$(document).ready(function() {
$.getJSON('http://www.url.com/?callback=?', function(data) {
$.each(data, function(index, entry) {
var htm开发者_JAVA技巧l = '<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);
});
});
});
Here is an example of the JSON data:
{
"AvatarUrl":"http://www.gravatar.com/avatar/35b2d5391e4a766e57d0d1f4a767f61f?s=120&d=retro",
"Id":4,
"FirstName":"Aimee",
"LastName":"Lacariere",
"Location":"Seattle, Washington"
}
First off this code:
var thisPic = $('.entry img');
Will return an array of all of the imgs created in the each() loop. Perhaps you meant to make the class value on the first divs unique?
But really you shouldn't need to call a function to set an attribute. Just add it to the string directly:
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>';
You should do it like this:
$(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);
});
});
});
As you can see, we're using append
instead of concatenating. Your error was in the var thisPic = $('.entry img');
selector, cause it will search in all the document. Whit this:
$('.entry img', $html);
we only select the image inside the just created html.
Hope this helps. Cheers
I beleive the problem is you are creating multiple divs of the class entry then reassigning the img src to the div each time you loop through your code. Rather than calling the createurl function add this line:
html += '<img src="' + entry.AvatarUrl + '"/>';
and remove the function
精彩评论