Javascript 为什么当我尝试将这些数字相乘时会得到NaN?
我尝试将两个数字相乘并在文本框中显示结果,但当我单击按钮时得到NaNJavascript 为什么当我尝试将这些数字相乘时会得到NaN?,javascript,Javascript,我尝试将两个数字相乘并在文本框中显示结果,但当我单击按钮时得到NaN var firstBox=parseFloat(document.getElementById('firstTxt').value); var secondBox=parseFloat(document.getElementById('secondTxt').value); var the_answer=document.getElementById('answer'); var calculate=d
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>
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结果=第一个方框*第二个方框;
答案。值=结果;
}
标题
当输入更改时,firstBox
和secondBox
变量不会更新其值
因此,在onclick处理程序内的行下方移动/复制:
var firstBox=parseFloat(document.getElementById('firstTxt').value);
var secondBox=parseFloat(document.getElementById('secondTxt').value);