Reputation: 31
I'm working on a program that picks an object from an array and displays a picture to a div. How could I take a picture from an object and display it? I was thinking something like this but it doesn't seem to work.
var pizza = {
crust: bread,
topping: sauce,
imgURL: 'www.pizza.com'
}
$('#mydiv').append(pizza.imgURL);
Upvotes: 0
Views: 52
Reputation: 463
Have you tried this?
$('#mydiv').append('<img src="' + pizza.imgURL + '"/>');
This appends an image in your #myDiv and sets it's image-source-url based on your pizza object
Upvotes: 1
Reputation: 4361
A solid solution would be to create the element via jQuery, set its src
to pizza.imgURL
, and pass the element to the append()
method. This ensures that the URL is properly escaped (it shouldn't be an issue, but it's certainly possible).
Here's a jsFiddle to prove that this works. However, of course, the image doesn't load because, well, it's not a valid image URL.
var pizza = {
crust: bread,
topping: sauce,
imgURL: 'www.pizza.com'
}
$('#mydiv').append($('<img>').prop({
src: imgURL,
// don't forget your alt attribute!
alt: 'pizza'
}));
Upvotes: 0