gpt4 book ai didi

Javascript - 输入值 NaN

转载 作者:行者123 更新时间:2023-12-01 01:49:43 24 4
gpt4 key购买 nike

我是 Javascript 新手,当时正在做一些 DOM 操作,我尝试创建 BMI( body 质量指数)计算器,即 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>

关于Javascript - 输入值 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com