2

このクエリを使用して、flickr アカウントから JSON フィードを解析し、そのフィードから最新の 12 枚の写真のコードを #photos という名前の div に挿入します。

<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 枚の写真をロードする必要があります。これを行うにはどうすればよいですか?

4

1 に答える 1

1

それらをすべて配列にダンプしてから、ランダムに要素をつなぎ合わせます。元の配列から実際に要素を削除するため.splice()、同じ項目を 2 回抽出する心配はありません。

$.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'
});
于 2013-05-15T13:35:50.477 に答える