index1.html
<!DOCTYPE html>
<html>
<head>
<script src="index1.js" charset="utf-8"></script>
</head>
<body>
<div id="active" class="arrow">
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
index1.js
let a =document.getElementById('active')
console.log(a)
控制台输出效果:
image.png
你是不是也疑惑,为什么会这样?其实这和浏览器加载的机制有关(自上而下),这是并未加载完成的情况。而我们只要改动引入js脚本的位置即可缓解这种尴尬的局面。

在来看看控制台的效果。

控制台不再是null了,是不是很神奇。
这是其中一个方法,这里我们还是有其他的方法的,我们不用调整脚本的放置位置,那就是用window.onload=function(){执行代码}将代码块包裹起来。

简单点理解就是把代码放进里面去运行。我们看看效果是一样的。

网友评论