Javascript 体重指数计算器

Javascript BMI Calculator

在 JSFiddle 中打印任何东西时遇到问题,尽管我觉得一切正常。我不确定为什么 HTML 没有显示答案,但欢迎任何帮助。谢谢!

HTML:

<h2>BMI Calculator</h2>
<p>
    Enter your weight in pounds:
    <input type="text" id="weight">
</p>

<p>
    Enter your height in inches:
    <input type="text" id="height">
</p>

<input type="button" onclick="bmiCalculator()" value="calculate">
<p id="output"></p>

Javascript:

function bmiCalculator() {
    var weight = Number(document.getElementById("weight").value);
    var height = Number(document.getElementById("height").value);
    var finalWeight = weight * .45;
    var finalHeight = height * .025;

    var BMI = (finalWeight / Math.pow(finalHeight, 2));

    document.getElementById("output").innerHTML = BMI;
}

您的代码中存在语法错误(您的 BMI 表达式中缺少右括号)。 这是固定代码(我只是在需要的地方添加了 )),在我看来它工作正常。

function bmiCalculator() {

  var weight = Number(document.getElementById("weight").value);
  var height = Number(document.getElementById("height").value);
  var finalWeight = weight * .45;
  var finalHeight = height * .025;


var BMI = (finalWeight / Math.pow(finalHeight, 2));

document.getElementById("output").innerHTML = BMI;

}
<h2>
 BMI Calculator
</h2>

<p>
  Enter your weight in pounds:
  <input type="text" id="weight">
</p>

<p>
  Enter your height in inches:
   <input type="text" id="height">
</p>

<input type="button" onclick="bmiCalculator()" value="calculate">
  <p id="output" ></p>

注意: 除非 Javascript 选项负载类型设置为 No wrap - in <body>[=15=,否则此代码将不适用于 jsfiddle.net ]

多亏了另一个堆栈,我发现了这一点:Onclick event not firing on jsfiddle.net

你忘了)

var BMI = (finalWeight / Math.pow(finalHeight, 2);

应该是

var BMI = (finalWeight / Math.pow(finalHeight, 2));

您的代码中缺少“)”。用这个更新你的脚本

 function bmiCalculator() {

            var weight = Number(document.getElementById("weight").value);
            var height = Number(document.getElementById("height").value);
            var finalWeight = weight * .45;
            var finalHeight = height * .025;


            var BMI = (finalWeight / Math.pow(finalHeight, 2));

            document.getElementById("output").innerHTML = BMI;

        }

希望这会有所帮助:)