我收到了Uncaught TypeError:无法将属性'onclick'设置为null? [英] i'm getting an Uncaught TypeError: Cannot set property 'onclick' of null?
本文介绍了我收到了Uncaught TypeError:无法将属性'onclick'设置为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下类型的未捕获类型错误:
未捕获的TypeError:无法将属性'onclick'设置为null
i'm getting uncaught type error of: Uncaught TypeError: Cannot set property '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。将代码移至页面末尾或将其放在onload处理程序中。
You're executing your JavaScript before the elements exist. Either move your code to the end of the page or put it within an onload handler.
Ex:
<!DOCTYPE html>
<html>
<head>
<title>dice app</title>
</head>
<body>
<button id="button">Roll Dice</button>
<script src="widget.js"></script>
</body>
</html>
这篇关于我收到了Uncaught TypeError:无法将属性'onclick'设置为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文