[英]How to display a randomly generated string (from array) again in another area?
Basically, I'm using HTML and JavaScript to make a simple rock, paper, scissors game where a button activates a randomly generated string from an array (rock, paper, or scissors).基本上,我使用 HTML 和 JavaScript 来制作一个简单的石头剪刀布游戏,其中一个按钮激活从数组(石头、剪刀布或布)中随机生成的字符串。 I already have it so that the button randomly generates a computer choice and it displays my choice (using radio buttons) in a box below.
我已经有了它,因此该按钮会随机生成一个计算机选择,并在下面的框中显示我的选择(使用单选按钮)。 I'm stuck because I don't know how to display the randomly generated computer choice again in another box.
我被卡住了,因为我不知道如何在另一个框中再次显示随机生成的计算机选择。
I tried using if else statements but I can't figure out how to reference the randomly chosen string from the array.我尝试使用 if else 语句,但我不知道如何从数组中引用随机选择的字符串。 Here is what I tried before within the html game:
这是我之前在 html 游戏中尝试过的:
<script>
function myFunction();{
if (document.getElementById("randomSelect")) = 'rock'{
document.getElementById('computerChoice').innerHTML = 'rock'
} if (document.getElementById("randomSelect")) = 'paper'{
document.getElementById('computerChoice').innerHTML = 'paper'
} if (document.getElementById("randomSelect")) = 'scissors'{
document.getElementById('computerChoice').innerHTML = 'scissors'
}
}
</script>
<p id = "computerChoice"></p>
Also, sorry if this makes no sense.另外,抱歉,如果这没有意义。 I'm new to coding.
我是编码新手。
Generate random number between 0 and 2 (Array Index).生成 0 到 2 之间的随机数(数组索引)。 Store items in an array and pull out based on random Index generated.
将项目存储在数组中并根据生成的随机索引拉出。
var items = ["rock", "paper", "scissors"]; document.getElementById("randomSelect").addEventListener('click', myFunction); function myFunction() { /*Generate random number between 0 and 2*/ var randomNum = Math.floor(Math.random() * 3); /*Set the random Item*/ document.getElementById('computerChoice').innerHTML = items[randomNum]; }
<p id="computerChoice"></p> <button type="button" id="randomSelect">Random</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.