为什么这个简单的JavaScript程序不起作用?

时间:2013-02-07 05:49:18

标签: javascript html

警报窗口给我留言NaN出了什么问题? 谢谢所有的帮助     

var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)

function calcBMI() {
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>


 <form action="" name="BMI">
<input type="text" name="weight" />
<input type="text" name="height" />
<input type="submit" onclick="alert(calcBMI())" />
</form>

3 个答案:

答案 0 :(得分:2)

<script type="text/javascript">
function calcBMI() {
var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>


 <form action="" name="BMI">
<input type="text" name="weight" />
<input type="text" name="height" />
<input type="submit" onclick="alert(calcBMI())" />
</form>

希望它现在有效:)

答案 1 :(得分:0)

您需要将变量移动到函数调用中。 *编辑..我被击败了。

<form action="" name="BMI">
  <input type="text" name="weight" />
  <input type="text" name="height" />
  <input type="submit" onclick="alert(calcBMI())" />
</form>

<script type="text/javascript">

function calcBMI() {
    var weight = parseFloat(document.BMI.weight.value)
    var height = parseFloat(document.BMI.height.value)
    var answer = weight * 703 / (height*height)
    console.log(weight);
    return answer;
}
</script>

答案 2 :(得分:0)

    function calcBMI() {
    var weight = parseFloat(document.BMI.weight.value)
var height = parseFloat(document.BMI.height.value)
var answer = weight * 703 / (height*height)
return answer;
  }
    </script>

本地和全局变量存在问题。当您单击该按钮时,该功能不会从文本框中获取值