当前位置:网站首页>浏览器的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> 
边栏推荐
猜你喜欢
随机推荐
[QNX Hypervisor 2.2用户手册]9.18 unsupported
mysql 查询表 所有字段
IOT物联网概述及应用层架构入门篇
MySQL 8.0.28 version installation and configuration method graphic tutorial
2022年100道最新软件测试面试题,常见面试题及答案汇总
MYSQL 唯一约束
MySQL 5.7详细下载安装配置教程
棋盘问题(DAY 94)
Redis常见题型
[网鼎杯 2020 青龙组]singal
系统(层次)聚类
迅为RK3568开发板编译Buildroot-全自动编译
pg数据库报错问题,有懂的吗
【语义分割】FCN
Mysql 回表
UE4 蓝图实现AI随机移动
【QT】Qt Creator生成动态库(DLL)并调用
元宇宙:活在未来
MySQL multi-table association one-to-many query to get the latest data
navicat新建数据库








