未捕获的TypeError:无法设置属性' value' of null,JavaScript

时间:2014-06-26 07:27:49

标签: javascript html

使用此代码时,我一直收到此错误消息。 SRC - > http://jsfiddle.net/MYG2C/1/

JS

    <input class="menu1" type="submit" value="Total : 0.00" onclick="m.getTotal()" id="total" />

HTML

var m = {
    total:0,
    getTotal: function () {
        this.total = this.total.toFixed(2);
        document.getElementByID("total").value = "Total : " + this.total;
    },
}
m.total = 5;
//Clicking the button should now update the text on the button.

2 个答案:

答案 0 :(得分:2)

两个问题......

  • getElementByID应为getElementById
  • this.total = this.total.toFixed(2);将首次使用,因为total是一个数字。之后它变成一个字符串,toFixed不是字符串
  • 上的有效方法

Updated Fiddle

答案 1 :(得分:1)

你有一个拼写为anthony chu,下面是修改后的脚本,用于检查类型并避免Uncaught TypeError。

var m = {
    total:8,
    getTotal: function () {
        if(typeof this.total == "number")
        {
        console.log("executed");
        this.total = this.total.toFixed(2);
        document.getElementById("total").value = "Total : " + this.total;
        }
    },
}

JSFIDDLE:http://jsfiddle.net/8J2G7/4/

相关问题