我使用此查询从flickr帐户解析JSON提要,并在名为#photos
的div中从该提要中注入最新12张照片的代码<script type="text/javascript">
// Set variables needed for query
var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
var ID = "<?php echo get_option('of_flickrid') ?>";
var jsonFormat = "&lang=en-us&format=json&jsoncallback=?";
var ajaxURL = URL + "?id=" + ID + jsonFormat;
// Get the last photos of the flickr account, parse it into HTML code
$.getJSON(ajaxURL, function(data){
var htmlString = '<a href="<?php echo get_option('of_flickr') ?>" target="_blank"><h1><?php echo get_option('of_photostext') ?></h1></a><br class="clear"/>';
// Now start cycling through our array of Flickr photo details
$.each(data.items, function(i,item){
// I only want the ickle square thumbnails
var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
// Here's where we piece together the HTML
htmlString += '<a href="' + item.link + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
htmlString += '" alt="'; htmlString += item.title + '" class="rounded"/>';
htmlString += '</a>';
if(i === 11){
return false;
}
});
// Pop our HTML in the #images DIV
$('#photos').html(htmlString);
}); // End getJSOON
</script>
但是我需要加载12张随机照片而不是最新的12张,我该怎么办?
答案 0 :(得分:1)
将它们全部转储到数组中,然后拼接出elements at random。由于.splice()
实际上从原始数组中删除了元素,因此您不必担心两次提取相同的项目。
$.getJSON(ajaxURL, function(data){
var items = data.items, // array
extract = [], // array
max = 12; // number of items to remove
for (var i=0; i<max; i++) {
var rand = Math.floor(Math.random()*items.length); // a random index
extract.push(items.splice(rand,1)[0]); // splice() returns an array
};
// do something with 'extract'
});