本文介绍了即使输入为整数,JavaScript也会返回NaN的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在输入框中输入一个整数,它仍然返回'NaN'.
I am typing an integer in the input box and it still returns 'NaN'.
function goldenFunctiona() {
a = document.getElementById("sidea");
parseInt(a, 10);
b = ((a + a) * (Math.pow(5, 0.5))) / 2;
document.getElementById("b").innerHTML = b;
}
<div id="top">
<p>Side a =</p>
<input id="sidea" type="number">
<button id="button" onclick="goldenFunctiona()" type="button">Find side b</button>
<p id="b"></p>
</div>
我不知道出了什么问题,但这可能真的很简单.预先感谢.
I don't know what's going wrong but it's probably something really simple.Thanks in advance.
推荐答案
document.getElementById("sidea")
不返回 number ,但返回元素.使用 document.getElementById("sidea").value
来获取元素值.
document.getElementById("sidea")
doesn't returns a number, but an element.Use document.getElementById("sidea").value
instead to get the element value.
所以:
function goldenFunctiona() {
var sideaVal = document.getElementById("sidea").value;
var a = parseInt(sideaVal , 10); // Get parseInt's return value or 'a' will still be a string
var b = ((a + a) * (Math.pow(5, 0.5))) / 2;
document.getElementById("b").innerHTML = b;
}
这篇关于即使输入为整数,JavaScript也会返回NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!