我尝试使用Javascript生成随机图像,但它无法正常工作。我的代码如下;我不知道这个功能是否正确。
//var imageDir = document.images;
var imageDir = [ 10 ];
var imageDir =
[
"cards/1.png",
"cards/2.png",
"cards/3.png",
"cards/4.png",
"cards/5.png",
"cards/6.png",
"cards/7.png",
"cards/8.png",
"cards/9.png",
"cards/10.png"
];
displayRandomImage = function(i, numberOfImages) {
for (var i = 0; i < imageDir.length; i++, i = parseInt(Math.random() * i))
{
return i = Math.random(i, numberOfImages - 1);
}
};
var imageDir = displayRandomImage(imageDir, 10);
for (var i = 0; i < imageDir.length; i++) {
document.getElementById("randimage" + i).innerHTML = "<img src='" + imageDir[ i ] + "' />"
}
答案 0 :(得分:0)
你想只挑选一张随机图片吗?或者以随机顺序显示数组中的所有图像?如果是后者,试试这个。
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
var imagePaths = shuffle([
"cards/1.png",
"cards/2.png",
"cards/3.png",
"cards/4.png",
"cards/5.png",
"cards/6.png",
"cards/7.png",
"cards/8.png",
"cards/9.png",
"cards/10.png"]);
for(var i = 0; i < imagePaths.length; i++) {
document.getElementById("randimage" + i).src = imagePaths[i];
}
请点击此处查看此操作的示例:http://jsfiddle.net/nSaAh/