2016-01-29 85 views
3

我正在製作一個遊戲,說一個隨機數點擊,然後它會告訴你它何時是對還是錯。我希望用戶決定他們想要多少輪並將其輸入到程序中。如何將輸入存儲到HTML和Javascript中的變量中?

//takes the number of rounds and puts it into a variable so it shows the amount of questions you want 
 
\t var numberOfRounds = parseInt(document.getElementById("numberOfRounds").value) //puts the input numberOfRounds in a variable. 
 
\t console.log(numberOfRounds); 
 
\t randomNumber = (Math.floor(Math.random() * 6)); 
 
\t console.log(randomNumber); 
 
\t 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>

+0

目前還不清楚你問什麼,也是你的HTML似乎是不完整的。 buttonColors函數又是什麼?它有什麼作用? –

+1

'document.getElementById(「numberOfRounds」)'給你找到的第一個元素,即'form'。儘管如此,這沒有任何價值。文檔中的「id」必須是唯一的。 – Teemu

回答

3

你的代碼是更多或更少的正確 - 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>

+0

謝謝。編輯。 – rphv

相關問題