Selecting a random image from a flickr set and appending it to a div
I've run into a bit of a problem and was hoping to get a little help. I am trying to select a r开发者_运维百科andom image from a flickr set and append it to a div to use as a background image. Here is the function:
$.getJSON("http://***", function (data){
var htmlString = "";
$.each(data.photoset.photo, function(i, item){
var bkg = data.photoset.photo[i];
var randomBkg = Math.floor(Math.random() * bkg.length);
htmlString += '<img src='+ randomBkg.url_o +' />';
return i < 0;
});
$('#bg').append(htmlString);
});
If i replace randomBkg.url_o with bkg.url_o it just returns the first image in the set. using it as i have above appends an image tag with "undefined" as the img src. Any help about where i am misguided would be super appreciated.
The image tag is "undefined" right now, because Math.floor
returns a Number
, and Numbers don't have the url_o
property. If you are just looking to pick out one image out of the set, you don't really need to use $.each
to iterate over all of the items. You should be able to do the following:
var index = Math.floor(Math.random() * data.photoset.photo.length);
var randomImage = data.photoset[index];
var htmlString = = '<img src='+ randomImage.url_o +' />';
精彩评论