可以通过创建一个可能图像的数组,打乱该数组,然后抓取前 4 个图像并附加到 div 来完成:
// randomize array function
Array.prototype.shuffle = function() {
var i = this.length, j, temp;
if ( i == 0 ) return this;
while ( --i ) {
j = Math.floor( Math.random() * ( i + 1 ) );
temp = this[i];
this[i] = this[j];
this[j] = temp;
}
return this;
}
// declare image data as array of objects
var images = [
{ src : 'images/image_01.jpg', href : 'page_082.html' },
{ src : 'images/image_02.jpg', href : 'page_083.html' },
{ src : 'images/image_03.jpg', href : 'page_084.html' },
{ src : 'images/image_04.jpg', href : 'page_085.html' },
{ src : 'images/image_05.jpg', href : 'page_086.html' },
{ src : 'images/image_06.jpg', href : 'page_087.html' }
];
$(document).ready(function(){
var img, anchor, div;
var cont = $('.socialphoto_container');
cont.children().remove();
images.shuffle();
for(var i=0; i<4; i++){
img = $('<img />', { src : images[i].src });
anchor = $('<a></a>', { href : images[i].href, target : '_self' });
div = $('<div></div>', { class : 'socialphoto' });
anchor.append(img);
div.append(anchor);
cont.append(div);
}
});
Array.shuffle()
是 Fisher-Yates 算法,取自here https://stackoverflow.com/questions/2450954/how-to-randomize-a-javascript-array.