JavaScript Null值错误

时间:2015-10-21 11:05:10

标签: javascript null

我已经使用Javascript创建了这个简单的应用程序,但是我一直收到一条错误,上面写着" Uncaught TypeError: Cannot read property 'value' of null"这发生在" var age = document.getElementById("age").value;"我一直在寻找问题的每一个地方,但我只是没有看到它。请查看我的代码并帮助我。谢谢!

<script>
        function calculateBMR()
    {
        var gender = document.getElementById("gender").value;
        var age = document.getElementById("age").value;
        var weigth = document.getElementById("weight").value;
        var heigth = document.getElementById("height").value;
        console.log(gender);
        if (gender == "male")
        {
            var result = 66 + ( 6.23 * weight) + ( 12.7 * height ) - ( 6.8 *age );

        }
        else if (gender == "female")
        {
            var result = 655 + ( 4.35 * weight ) + ( 4.7 * height ) - ( 4.7 * age );
        }
        document.bmrForm.bmr.value = result;
    };
    </script>
    <form name = "bmrForm">
        Gender:
            <br />
        <select id="gender">
        <option value="male">male</option>
        <option value="female">female</option>
        </select>
            <br />
        Age:
            <br />
        <input type = "text" name ="age" size = "10">
            <br />
        Weigth (lb.) :
            <br />
        <input type = "text" name ="weight" size = "10">
            <br />
        Heigth (inches) :
            <br />
        <input type = "text" name = "height" size = "10">
            <br />
            <br />
        <input type = "button" value = "Calculate BMR" onClick = "calculateBMR();">
            <br />
            <br />
          BMR:
            <br />
        <input type = "text" name = "bmr">
    </form>

1 个答案:

答案 0 :(得分:0)

您正在寻找ID为ageheightweight的元素,而没有包含这些ID的HTML元素。

尝试使用它们:

<input type = "text" name ="age" size = "10" id="age">
<input type = "text" name ="weight" size = "10" id="weight">
<input type = "text" name ="height" size = "10" id="height">

修改:
您不应该直接使用document.getElementById(...).value,因为可以未定义,具体取决于它使用的HTML。此外,如果用户输入非数字值,您将保证会出现某种无效结果(例外,计算错误等)。

因此,您应该相应地更改您的JavaScript:

var ageElement = document.getElementById('age');

if (ageElement != undefined)
    age = Number(ageElement.value);

if (Number.isNaN(age))
    // Do your calculations.