JS event triggered the error "Can not set property 'onclick' of null"

JS event of an error "Can not set property 'onclick' of null"

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>事件</title>
	<script>
		var btn1 = document.getElementById('btn1');
		var demo1 = document.getElementById('demo1');
		// onclick事件
		btn1.onclick = function () {
			demo1.innerHTML = 'hello world!';
		}
	</script>
</head>
<body>
	<button id="btn1">点我</button>
	<p id="demo1"></p>
</body>
</html>

The implementation of the above code, an error will be reported as follows:
Here Insert Picture Description
After js code will put the bottom of the load, it can normally run

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>事件</title>
	
</head>
<body>
	<button id="btn1">点我</button>
	<p id="demo1"></p>

	<script>
		var btn1 = document.getElementById('btn1');
		var demo1 = document.getElementById('demo1');
		// onclick事件
		btn1.onclick = function () {
			demo1.innerHTML = 'hello world!';
		}
	</script>
</body>
</html>

Analysis of reasons:
when the js code or js files placed between the head, such as if bound onclick or onmouseover event, similar to the error console will be reported as shown above. Because the browser loads html document order is from top to bottom, complete load button node js code before execution. Browser parses top down, the node can not find a button onclick binding, then error.

Solution:

  1. Js js code or the external file is loaded on the bottom
  2. Use window.onload = function () {} package contents js
Released six original articles · won praise 0 · Views 926

Guess you like

Origin blog.csdn.net/sinat_41374125/article/details/104712311