【问题标题】:i'm getting an Uncaught TypeError: Cannot set property 'onclick' of null? [duplicate]我收到未捕获的类型错误:无法将属性“onclick”设置为 null? [复制]
【发布时间】:2016-02-21 21:01:07
【问题描述】:

我收到以下未捕获的类型错误: 未捕获的类型错误:无法设置属性 'onclick' of null

<!DOCTYPE html>
<html>
    <head>
        <title>dice app</title>
        <script src="widget.js"></script>
    </head>
    <body>
        <button id="button">Roll Dice</button>
    </body>
</html>

js代码:

var button = document.getElementById("button");

button.onclick = function() {// error
    var print = dice.roll();
    printNumber(print);
};

【问题讨论】:

标签: javascript dom


【解决方案1】:

将脚本移动到 HTML 中的按钮之后。目前正在评估脚本,但尚未创建 HTML 元素。

【讨论】:

    【解决方案2】:

    您在元素存在之前执行您的 JavaScript。将您的代码移动到页面末尾或将其放在 onload 处理程序中。

    例如:

    <!DOCTYPE html>
    <html>
        <head>
            <title>dice app</title>
        </head>
        <body>
            <button id="button">Roll Dice</button>
            <script src="widget.js"></script>
        </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2018-01-03
      • 2014-02-07
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-01
      • 2014-06-26
      • 2014-03-06
      相关资源
      最近更新 更多