javascript - 如何将输入存储到 HTML 和 Javascript 中的变量中?

标签 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>

最佳答案

您的代码或多或少是正确的 - 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/

相关文章:

javascript - 我如何存储 React 输入元素的值并在其他元素中使用它

python - 猜测当前表示为字符串的数据类型的方法

javascript - Web 应用程序作为程序运行,无需浏览器

javascript - Handlebars 中的 {{#_}} ... {{/_}} block 是什么意思?

javascript - 正则表达式从 url 字符串解析动态参数

html - float 尴尬局面

html - CSS 继承对于选项卡无法正常工作

html - 导航菜单 "pulled left"使用 Bootstrap : submenu also pulled left

javascript - 如何从 document.form 获取 html 元素

Javascript:仅允许小于输入初始值的值