我正在制作一个游戏,它会说一个随机数供您点击,然后它会告诉您它是对还是错。我希望用户决定他们想要多少轮并将其输入到程序中。
//takes the number of rounds and puts it into a variable so it shows the amount of questions you want
var numberOfRounds = parseInt( document.getElementById( "numberOfRounds" ).value ) //puts the input numberOfRounds in a variable.
console.log(numberOfRounds);
randomNumber = ( Math.floor(Math.random() * 6));
console.log(randomNumber);
buttonColors();
<font size="6"><center><strong><p id="startScreen">Welcome to the Random Color Game.</p></strong></center></font>
<font size="4"><center><p id="startScreen2">How many many rounds of the game would you like?</p>
<form id="numberOfRounds"><p id="startScreen3">I would like <input id="numberOfRounds" type="number" min="1" max="20" name="numberOfRounds" style = "width:100px; height:50px;"> rounds.</p>
<p id="startScreen5">To start playing the game, push begin.</p></center></font>
最佳答案
您的代码或多或少是正确的 - document.getElementById("numberOfRounds").value
将从 input
中获取值元素,假设这是唯一带有 id="numberOfRounds"
的元素( id
s 在文档中应该是唯一的)。
我稍微重构了您的代码并添加了一个“开始”按钮,该按钮从 <input>
中获取值。元素并将其显示给用户。
//puts the input numberOfRounds in a variable.
function getNumberOfRounds() {
var setNumberOfRoundsElement = document.getElementById("setNumberOfRounds");
var myNumberOfRoundsElement = document.getElementById("myNumberOfRounds");
var numberOfRounds = parseInt(setNumberOfRoundsElement.value);
myNumberOfRoundsElement.innerHTML = "You chose " + numberOfRounds + " rounds!";
}
body {
text-align: center;
}
<h1>Welcome to the Random Color Game.</h1>
<div id="myNumberOfRounds">
How many many rounds of the game would you like?
<p>
I would like
<input id="setNumberOfRounds" type="number" min="1" max="20" name="numberOfRounds">
rounds.
</p>
To start playing the game, push begin.
<p>
<button onclick="getNumberOfRounds()">Begin</button>
</p>
</div>
关于javascript - 如何将输入存储到 HTML 和 Javascript 中的变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35088673/