Javascript-输入值NaN

时间:2018-08-01 20:12:42

标签: javascript

我是Java的新手,我正在做一些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>

非常感谢大家!

3 个答案:

答案 0 :(得分:3)

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

<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>

答案 1 :(得分:1)

即使在单击按钮之前,您仍在获取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>

答案 2 :(得分:-2)

由于您输入的内容是数字,因此您应该这样做

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

并将计算结果放在按钮内,单击event,否则在页面加载后将执行计算,并且您将收到NaN警报。