当前位置:网站首页>浏览器的onload事件
浏览器的onload事件
2022-08-02 05:01:00 【记忆怪 bug】
如下代码,因为代码从上到下执行,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> 
边栏推荐
猜你喜欢
随机推荐
Google Chrome(谷歌浏览器)安装使用
mysql练习题
mysql 存储过程详解
MySQL String Concatenation - Various String Concatenation Practical Cases
元宇宙:活在未来
navicat无法连接mysql超详细处理方法
golang泛型
11种你需要了解的物联网(IoT)协议
迅为RK3568开发板编译Buildroot-全自动编译
WiFi、蓝牙、zigbee锁与NB、Cat.1锁的区别
【热题】LeetCode 热题 HOT 100分类+题解
MobaXsterm如何使用
Matlab paper illustration drawing template No. 41 - bubble chart (bubblechart)
Go语学习笔记 - 处理超时问题 - Context使用 从零开始Go语言
Towhee 每周模型
What do interview test engineers usually ask?The test supervisor tells you
CNN 理解神经网络中卷积(大小,通道数,深度)
【HCIE】NO.30 OSPFv3的基本配置
Mycat2.0搭建教程
MySQL 8.0.29 set and modify the default password









