问题分析:当JS文件放在head标签里中时,并且绑定了onclick事件,就出现了这个错误
原因:
W3School中介绍浏览器先加载完按钮节点才执行JS,当浏览器自顶向下解析时,找不到onclick绑定的按钮节点了
如下面这个例子:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>事件</title>
<script>
var Btn = document.getElementById('btn');
Btn.onclick = function(){
console.log("push the button ");
}
</script>
</head>
<body>
<button id="btn">计算</button>
</body>
</html>
就会出现这个这个错误,如下图:
解决办法一:把JS内容用window.οnlοad=function(){ }包裹起来
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>事件</title>
<script>
window.onload = function () {
var Btn = document.getElementById('btn');
Btn.onclick = function () {
console.log("push the button ");
}
}
</script>
</head>
<body>
<button id="btn">计算</button>
</body>
</html>
解决办法二:把js文件放在底部加载
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>事件</title>
</head>
<body>
<button id="btn">计算</button>
<script>
var Btn = document.getElementById('btn');
Btn.onclick = function () {
console.log("push the button ");
}
</script>
</body>
</html>