·下面这种写法是有问题的,因为JS的执行顺序是从上到下的,现在我们的JS使用了还没有存在的div所以,就会在console中看到这样的错误。
<!DOCTYPE html>
<html>
<head>
<title>网页加载</title>
<meta charset="utf-8" />
</head>
<script>
var oDiv = document.getElementById('xxx');
alert(oDiv);
</script>
<body>
<div id="xxx">xxxx</div>
</body>
</html>
但我们说过JS的代码是可以放在网页的任何地方的,那么该怎么解决呢?
这就用上了onload和onreay这两个JS事件了。
其中:onready不加载类似音频、视频这样的资源,而onload会加载网页的全部内容。
根据自己的需求进行选择。
下面是改进之后的代码:
<!DOCTYPE html>
<html>
<head>
<title>网页加载</title>
<meta charset="utf-8" />
</head>
<script>
window.onload = function () {
var oDiv = document.getElementById('xxx');
alert(oDiv);
};
</script>
<body>
<div id="xxx">xxxx</div>
</body>
</html>
执行之后的效果: