簡體   English   中英

為什么當我嘗試將這些數字相乘時會得到 NaN?

[英]why do i get NaN when i try to multiply these numbers?

我嘗試將兩個數字相乘並將結果顯示在文本框中,但是當我單擊按鈕時得到 NaN。

var firstBox=parseFloat(document.getElementById('firstTxt').value);
    var secondBox=parseFloat(document.getElementById('secondTxt').value);
    var the_answer=document.getElementById('answer');
    var calculate=document.getElementById('btn');
    
    calculate.onclick=function(){
      var result= firstBox*secondBox;
      the_answer.value=result;
    }
    
    
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8">
        <title>title</title>
      </head>
      <body style="background-color: cadetblue;">
      <p><input type="text" id="firstTxt"/> </p>
      <p><input type="text" id="secondTxt"/> </p>
      <p><input type="button" id="btn" value="Calculate"> </p>
      <p><input type="text" id="answer"/> </p>
    <script src="practice.js"></script>
      </body> 
    </html>

當輸入更改時, firstBoxsecondBox變量不會更新其值。

因此,在 onclick 處理程序內移動/復制以下幾行:

var firstBox=parseFloat(document.getElementById('firstTxt').value);
var secondBox=parseFloat(document.getElementById('secondTxt').value);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM