Cannot set property 'onclick' of null的问题——调用JS文件出错的问题

Cannot set property 'onclick' of null的问题 

转载自:https://my.oschina.net/ximidao/blog/351017

今天看了一个W3School JS点击事件的测试案例,详情页:http://www.w3school.com.cn/tiy/t.asp?f=js_dom_event_onclick4,其代码为:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<p>点击按钮就可以执行 <em>displayDate()</em> 函数。</p>

<button id="myBtn">点击这里</button>

<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>

<p id="demo"></p>

</body>
</html>

点击效果正常,而我平时测试代码的时候一般习惯把JS代码写在head标签里面,上述的代码如果将JS代码移到head标签,浏览器就会报错,提示:Uncaught TypeError: Cannot set property 'onclick' of null。

分析了一下代码,W3School的写法是浏览器先加载完按钮节点才执行的JS,因此我将代码改为:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.onload=function(){
	document.getElementById("myBtn").onclick=function(){displayDate()};
	function displayDate(){
		document.getElementById("demo").innerHTML=Date();
	}
}

</script>
</head>
<body>

<p>点击按钮就可以执行 <em>displayDate()</em> 函数。</p> <button id="myBtn">点击这里</button>

<p id="demo"></p>


</body>
</html>

测试通过,说明节点需要先加载完才能执行onclick事件。

原文地址:https://www.cnblogs.com/LinQingYang/p/11875666.html