为什么我无法使用此javascript代码?

时间:2014-07-17 16:28:12

标签: javascript

我用JavaScript编写了一个计算您的BMI的网页,它似乎可以正常工作但是当我点击计算按钮时会弹出一个警告框并说“你的BMI是NaN”。我知道NaN代表的不是数字。我只是想知道为什么我不能让它工作。

<!DOCTYPE html>

<html>
<head>

    <title>BMI</title>

</head>

<body>
    <p>Your weight:<input type="number" id="value1" /></p>

    <p>Your height (in inches):<input type="number" id="value2" /></p>

<script>

    function calc() {
    var data1 = document.getElementById("value1");
    var data2 = document.getElementById("value2");
    var weight = (data1 * 703);
    var height = (weight) / (data2 * data2);
    alert("Your BMI is " + height);
    };

    </script>

    <button onclick="calc()">Calculate</button>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

您必须获取data1和data2的内部值。

<!DOCTYPE html>

<html>
<head>

    <title>BMI</title>

</head>

<body>
    <p>Your weight:<input type="number" id="value1" /></p>

    <p>Your height (in inches):<input type="number" id="value2" /></p>

<script>

    function calc() {
    var data1 = parseFloat(document.getElementById("value1").value);
    var data2 = parseFloat(document.getElementById("value2").value);
    var weight = (data1 * 703);
    var height = (weight) / (data2 * data2);
    alert("Your BMI is " + height);
    };

    </script>

    <button onclick="calc()">Calculate</button>

</body>
</html>

答案 1 :(得分:0)

这是一个小提琴: http://jsfiddle.net/wYfq8/

function calc() {
    var data1 = document.getElementById("value1").value;
    var data2 = document.getElementById("value2").value;
    var weight = (data1 * 703);
    var height = (weight) / (data2 * data2);
    alert("Your BMI is " + height);
};