如下代码,因为代码从上到下执行,btn节点还未创建好就去获取会报错
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
</style>
<script>
console.log(btn) //报错, Uncaught ReferenceError: btn is not defined
</script>
</head>
<body>
<button id="btn">点我</button>
</body>
</html>
解决方式:利用onload事件
onload 事件会在页面或图像加载完成后立即发生。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script>
window.onload = function () {
//页面所有的资源加载完后执行
console.log('btn加载完成后打印', btn)
//btn加载完成后打印 <button id="btn">点我</button>
}
</script>
</head>
<body>
<button id="btn">点我</button>
</body>
</html>
onload 通常用于 <body> 元素,在页面完全载入后(包括图片、css文件等等。)执行脚本代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
height: 3000px;
}
</style>
<script>
//onload 通常用于 <body> 元素
function funct() {
console.log('onload事件触发了')
}
</script>
</head>
<body onload="funct()">
</body>
</html>