【问题标题】:Trying to make a BMI Calculator on JS, the calculation always returns 'NaN'试图在JS上做一个BMI计算器,计算总是返回\'NaN\'
【发布时间】:2022-08-16 23:49:06
【问题描述】:

我正在尝试在 JS 上创建一个 BMI 计算器。我遇到了计算本身的问题:它总是返回 \'NaN\'。我尝试使用 parseInt()、parseFloat()、Number(),它没有工作。我知道我的问题出在我的 \'imc\' 变量中,因为当我输入数字而不是 \'height\' 和 \'weight\' 时,它不再返回 \'NaN\',但我不\'不知道到底是什么问题。另外,我在控制台中没有任何错误。任何人都可以帮助我吗?

这是我的代码:

HTML:


<html lang=\"fr\">

<head>

  <meta charset=\"utf-8\">

  <title>Calculateur d\'IMC</title>

  <link rel=\"stylesheet\" href=\"imc.css\">

  <script src=\"imc.js\"></script>

</head>

<body>

<h1>Calculateur d\'IMC</h1>

<h2>Bienvenue! Entrez vos informations ci-dessous pour calculer votre IMC.</h2>

<div id=\"calcul\">
    <h3>Poids:</h3>
    <input type=\"number\" id=\"weightInput\" placeholder=\"Votre poids...\"></input>

    <h3>Taille:</h3>
    <input type=\"number\" id=\"heightInput\" placeholder=\"Votre taille...\"></input><br/>
</div>

<button onclick=\"calculate()\" id=\"button1\">Calculez!</button>

<div id=\"result\"></div>

</body>

<script src=\"imc.js\"></script>

</html>

JS:


var height = document.querySelector(\'#heightInput\'.value);

var element = document.querySelector(\'button\');


function calculate() {
    let imc = (weight / (height) **2);
    console.log(imc);
    alert(\'Vous avez un IMC de \' + imc + \'!\');
    return imc;
}

谢谢!

  • 应该是document.querySelector(\'#heightInput\').value;
  • 此外,如果您的代码与 weight 有相同的错误,也应该修复。
  • 你也应该得到体重和身高里面calculate() 函数,以便您获得新的值。
  • 有用!谢谢!是document.querySelector(\'heightInput\'.value),因为当我像你一样写它时,在控制台中会出现错误:Uncaught TypeError: Cannot read properties of null (reading \'value\')
  • 好吧,如果该代码运行HTML 被解析,该元素将不可用。如果您将代码放在函数中,那将有很大帮助。

标签: javascript html


【解决方案1】:

我没能弄清楚为什么它会打印出 NaN 但我修复了它,它似乎工作正常

var element = document.querySelector('button');


function calculate() {
    var height = new Number(document.getElementById("heightInput").value);
    var weight = new Number(document.getElementById("weightInput").value);
    let imc = (weight / (height) **2);
    console.log(imc);
    alert('Vous avez un IMC de ' + imc + '!');
    return imc;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    相关资源
    最近更新 更多