![](/img/trans.png)
[英]How to create a random number generator function using JavaScript without using the Math.random() function?
[英]JS Toss function using random number generator 0 to 1
我似乎无法正常运行以下内容:
function toss()
{
//If both coins come up HEADS or TAILS, the player wins. Otherwise the player loses.
//random number generator 0 to 1
//change image source using getElementById to div id coinA and coinB
//if random numbers same, set resultText innerHTML to "You Win"
//var x = Math.floor(Math.random() * (1 - 0 + 1)) + 0;
var x = Math.floor(Math.random()*2);
var coinImg = document.querySelectorAll("#coinA, #coinB");
if (x == 0){
coinImg.src = "images/coin0.png";
document.getElementById("resultText").innerHTML = "You Lost";
} else {
coinImg.src = "images/coin1.png";
document.getElementById("resultText").innerHTML = "You Win";
}
}
Here is the HTML:
<img src="images/coin1.png" id="coinA" width="100" height="100" alt="coin">
<img src="images/coin1.png" id="coinB" width="100" height="100" alt="coin">
<button type="button" onclick="toss()">Go</button>
<div id="resultText">Press GO to play!</div>
目前,这是告诉我“ You Lost”,当两个都是正面时...正面的图像是coin0而正面的图像是coin1。
您需要选择要使用的coinImg
,因为querySelectorAll
返回几个元素
另外,您可能只想显示/隐藏正确的硬币( jsfiddle此处 )
var x = Math.round(Math.random()); // x is always 0 or 1
var coins = document.querySelectorAll("#coinA, #coinB");
for (var i = 0; i < coins.length; i++) {
coins[i].setAttribute('style', 'display: none');
}
var coin = coins[x];
coin.setAttribute('style', 'display: block');
HTML也需要更新
<div id="coinA">
<p>You Lost</p>
<img src="images/coin0.png" width="100" height="100" alt="coin">
</div>
<div id="coinB">
<p>You Win</p>
<img src="images/coin1.png" width="100" height="100" alt="coin">
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.