MathGame未捕获的TypeError:无法将属性'onclick'设置为null

时间:2018-11-24 11:22:56

标签: javascript

我正在尝试制作数学游戏,但是在开始游戏中设置属性时。

//if we click on the start/reset`enter code here`
document.getElementById("startreset").onclick = function() {
    //if we are playing
    if(playing == true) {
        location.reload(); // reload page
    } else{ //if we are not playing
        //set score to 0enter code here

在控制台中,我得到MathGameJS.js:5 Uncaught TypeError:无法将属性'onclick'设置为null,感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

问题似乎是您在加载元素之前正在执行脚本。

我假定此脚本已添加到MathGame.js文件中,该文件是在创建DOM之前添加的。

这里的解决方案是在DOM准备就绪后执行脚本,例如:

window.onload = function(){
    document.getElementById("startreset").onclick=function(){
        //your code
    }
}

所有处理DOM元素的JavaScript代码(如上述代码)必须在DOM加载后执行。

相关问题