如何在HTML和Javascript中将输入存储到变量中?

时间:2016-01-29 15:56:20

标签: javascript html input

我正在制作一个游戏,上面写着一个随机数字,然后它会告诉你何时是对还是错。我希望用户决定他们想要多少回合并将其输入到程序中。



//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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您的代码或多或少是正确的 - executeScript将从document.getElementById("numberOfRounds").value元素中获取值,假设inputid="numberOfRounds" {{1} s在文档中应该是唯一的。)

我稍微重构了你的代码并添加了一个&#34; Begin&#34;按钮,它从id元素获取值并将其显示给用户。

&#13;
&#13;
<input>
&#13;
//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!";
}
&#13;
body {
  text-align: center;
}
&#13;
&#13;
&#13;