Javascript BMI计算器

时间:2016-09-26 08:25:56

标签: javascript html jsfiddle

无法在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;
}

3 个答案:

答案 0 :(得分:1)

您的代码中存在语法错误(您在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>

注意:此代码无法在jsfiddle.net上运行,除非Javascript选项加载类型设置为No wrap - in <body>

我发现这要归功于另一个堆栈:Onclick event not firing on jsfiddle.net

答案 1 :(得分:0)

您忘记了)

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

应该是

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

答案 2 :(得分:0)

你错过了一个&#39;)&#39;在你的代码中。使用此

更新脚本
 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;

        }

希望这会有所帮助:)