简体   繁体   English

为什么我的parseFloat函数不能正常工作?

[英]Why does my parseFloat function not work properly?

When I do this exercise below, I have this problem that I cannot get the result, I attempt to input a number in num1 and a number in num2 , after that I click the calculate button I hope get the answer. 当我在下面进行练习时,遇到无法获取结果的问题,我尝试在num1输入一个数字,在num2输入一个数字,然后单击计算按钮,希望得到答案。 I checked the Chrome developer tool, it turned out that the num3 is NaN . 我检查了Chrome开发人员工具,结果发现num3NaN Why it's a NaN ? 为什么是NaN

 var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; var num3 = parseFloat(num1)+parseFloat(num2); var btn = document.getElementById("btn"); btn.onclick=function () { console.log(num3); console.log(parseFloat(num1)); }; 
 <input type="text" name="num1" id="num1"> <input type="text" name="num2" id="num2"> <button class="btn" id="btn">calculate</button> 

The value assigned to num1 during page load will not be updated magically when you change it later and click button. 稍后更改并单击按钮时,页面加载期间分配给num1的值不会神奇地更新。 So you need to retrieve it again. 因此,您需要再次检索它。 Just store HTMLInputElement in variable instead of its value: 只需将HTMLInputElement存储在变量而不是其值中:

var num1Input = document.getElementById('num1');

btn.onclick = function () {
  var num1 = num1Input.value;
  console.log(parseFloat(num1));      
};  

Move the variables inside the function: 在函数内移动变量:

 var btn = document.getElementById("btn"); btn.onclick=function () { var num1 = document.getElementById('num1').value; var num2 = document.getElementById('num2').value; var num3 = parseFloat(num1)+parseFloat(num2); console.log(num3); console.log(parseFloat(num1)); }; 
 <input type="text" name="num1" id="num1"> <input type="text" name="num2" id="num2"> <button class="btn" id="btn">calculate</button> 

Actually, you are doing wrong here, you getting element value before you enter values in input fields, the accurate code is below 实际上,您在这里做错了,在输入字段中输入值之前先获取了元素值,下面是准确的代码

var btn = document.getElementById("btn");
    btn.onclick=function () {
        var num1 = document.getElementById('num1').value;
        var num2 = document.getElementById('num2').value;
        var num3 = parseFloat(num1)+parseFloat(num2);
        console.log(num3);  
        console.log(parseFloat(num1));      
    };  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM