[英]How to make user input stored as JavaScript Variable for later use
我正在嘗試編寫一個程序,該程序允許用戶鍵入輸入,然后按下按鈕並打印輸入。 我似乎無法讓 JavaScript 保存用戶輸入。 我認為這與文本輸入字段的 value 屬性沒有更新有關,因此 JavaScript 無法檢索它。 我不知道如何解決這個問題,因此無法確定這是否是導致問題的原因。 任何幫助,將不勝感激。
var n = document.getElementById('userInput').value; function runCode() { document.getElementById('test').innerHTML = n; }
<input type="text" id="userInput"> <button type=button id="btn" onclick="runCode()">Click Me!</button> <p id="test">Orginal Text</p>
由於您在頁面加載時取值為空,因此您應該在點擊處理函數中取值。
請注意:如果值是純字符串(不是 htmlString)而不是innerHTML
,最好使用textContent
或innerText
屬性。
<input type="text" id="userInput"> <button type=button id="btn" onclick="runCode()"> Click Me! </button> <p id="test"> Orginal Text </p> <script> //console.log(document.getElementById('userInput').value == "") // true function runCode() { var n = document.getElementById('userInput').value; document.getElementById('test').textContent = n; } </script>
您在 JS 執行開始時引用輸入的值,該值將具有輸入的初始值,即空字符串。
嘗試把這個var n = document.getElementById('userInput').value;
函數內部
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.