Javascript - Input Value NaN



我是Javascript的新手,我正在做一些DOM操作,我试图创建BMI(体重指数(计算器,它是bodyMass/(bodyWeight*bodyWeight(。

然后我做了一些代码:

HTML:

var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
document.getElementById("check").onclick = function() {
alert(BMI);
}
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>

您需要在点击按钮时计算体重指数,而不是在页面加载时。通过不将代码放在事件处理程序中,可以在输入任何值之前计算所有内容。

<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
alert(BMI);
}
</script>

要确保在发出警报之前该值不是NaN,请使用isNaN

<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
if(!isNaN(BMI)){
alert(BMI);
} else {
alert("Please enter two valid numbers!");
}
}
</script>

您甚至在点击按钮之前就已经获得了bodyWeigt和bodyMass的值,在这个阶段(解析它们之后(,它们当然不是数字(NaN(。

点击按钮即可获取值,即当用户(希望(输入了一些有效值时。。。

document.getElementById("check").onclick = function() {
var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value);
bodyWeight = parseInt(document.getElementById("bodyWeight").value);
var BMI = bodyMass / (bodyWeight * bodyWeight); 
alert(BMI);
}
<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>

因为您的输入是数字,所以您应该执行

<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">

并将计算放在按钮内单击event,否则一旦页面加载,计算就会执行,您将收到NaN警报。

最新更新