Uncaught TypeError: Cannot set property 'onclick' of null
未捕获的TypeError:无法将属性“onclick”设置为null
问题分析:当JS文件放在head标签里中时,并且绑定了onclick事件,就出现了这个错误
原因:W3School中介绍浏览器先加载完按钮节点才执行JS,当浏览器自顶向下解析时,找不到onclick绑定的按钮节点了
报错代码:
<html>
<head>
<meta charset="utf-8">
<title>111</title>
<script type="text/javascript">
var add = document.getElementById("a");
add.onclick = function(){
alert("呵呵你个呵呵!!!");
}
</script>
</head>
<body>
<a href="javascript:;" id="a">点我</a>
</body>
</html>
解决方案一:把JS内容用window.οnlοad=function(){ }包裹起来
<html>
<head>
<meta charset="utf-8">
<title>111</title>
<script type="text/javascript">
window.onload = function(){
var add = document.getElementById("a");
add.onclick = function(){
alert("呵呵你个呵呵!!!");
}
}
</script>
</head>
<body>
<a href="javascript:;" id="a">点我</a>
</body>
</html>
解决方法二:将JS文件放在底部加载
<html>
<head>
<meta charset="utf-8">
<title>111</title>
</head>
<body>
<a href="javascript:;" id="a">点我</a>
<script type="text/javascript">
var add = document.getElementById("a");
add.onclick = function(){
alert("呵呵你个呵呵!!!");
}
</script>
</body>
</html>