JavaScript Uncaught TypeError: Cannot set property ‘onclick’ of null
错误示例:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
var obj = document.getElementById("check");
obj.onclick = judge;
function judge(){
var tem = obj.checked;
alert(tem);
}
</script>
<title></title>
</head>
<body>
<input name="checkbox" id="check" type="checkbox"/>box1
<input name="checkbox" type="checkbox" />box2
<input name="checkbox" type="checkbox" />box3
</body>
</html>
浏览器中,先加载完节点再执行JavaScript代码。当浏览器自上向下解析时找不到绑定按钮的节点,自然会报错。
解决方法一:
把所要执行的JavaScript代码用window.onload() = function (){}括起来。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
window.onload() = function (){
var obj = document.getElementById("check");
obj.onclick = judge;
function judge(){
var tem = obj.checked;
alert(tem);
}
}
</script>
<title></title>
</head>
<body>
<input name="checkbox" id="check" type="checkbox"/>box1
<input name="checkbox" type="checkbox" />box2
<input name="checkbox" type="checkbox" />box3
</body>
</html>
解决方法二:
把JavaScript代码放在文档底部执行。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input name="checkbox" id="check" type="checkbox"/>box1
<input name="checkbox" type="checkbox" />box2
<input name="checkbox" type="checkbox" />box3
<script type="text/javascript">
var obj = document.getElementById("check");
obj.onclick = judge;
function judge(){
var tem = obj.checked;
alert(tem);
}
</script>
</body>
</html>