我在玩JavaScript,并尝试选择一些随机图像。
我真正想做的是:
我在PHP中有$totalsixes = rand(1,6);
,假设它选择了4。然后在JavaScript中,我想显示4个数字为6的图像和2个数字为1-5的随机数字的图像。
以下是我迄今为止所尝试的:
<?php
$totalsixes = rand(1,6);
?>
<script type="text/javascript">
function shuffle(o){
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([
"http://website.com/spill2/terninger/1.gif",
"http://website.com/spill2/terninger/2.gif",
"http://website.com/spill2/terninger/3.gif",
"http://website.com/spill2/terninger/4.gif",
"http://website.com/spill2/terninger/5.gif",
"http://website.com/spill2/terninger/6.gif"]);
for(var i = 0; i < imagePaths.length; i++) {
document.getElementById("randterning" + i).src = imagePaths[i];
}
</script>
正如你可能在上面看到的那样,$totalsixes在代码中还没有任何意义,因为我不知道如何告诉JavaScript显示六个骰子中的X($totalsixes选择了X),而且我也不知道如何让JavaScript为其他骰子选择一个随机数。总共有6个骰子。
我想做的一个例子的屏幕截图:
http://prntscr.com/9iqiag
<?php $totalsixes = rand(1,6); ?>
<script type="text/javascript">
function shuffle(o){
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 = [
"http://website.com/spill2/terninger/1.gif",
"http://website.com/spill2/terninger/2.gif",
"http://website.com/spill2/terninger/3.gif",
"http://website.com/spill2/terninger/4.gif",
"http://website.com/spill2/terninger/5.gif",
"http://website.com/spill2/terninger/6.gif"];
var images = []; // <- edit here
for(var x= 0 ; x<6; x++){
images[x] = x < <?echo $totalsixes?> ? imagePaths[5] : imagePaths[Math.floor(Math.random() * 5)];
//^ edit here
}
images = shuffle(images);
for(var i = 0; i < imagePaths.length; i++) {
document.getElementById("randterning" + i).src = images[i];
}
</script>
如果我理解正确的话,结果是一个有"rand"六个的表,其他的都是随机骰子,但有六个