我正在使用 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 个骰子。
我想要制作的示例的屏幕截图:
最佳答案
<?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”六的表,所有其他都是随机骰子,但六个
关于javascript - PHP/JavaScript 随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34472483/