📜  onload 页面数据 (1)

📅  最后修改于: 2023-12-03 15:18:06.826000             🧑  作者: Mango

Onload 页面数据

什么是 onload 事件?

onload 事件是指在页面的所有元素(包括图片,视频等)都已经加载完毕后触发的事件。在网页中,当所有的资源都加载完成以后,我们可以对页面进行操作。

<!DOCTYPE html>
<html>
<head>
	<title>Onload Event</title>
	<script>
		window.onload = function () {
			alert("页面加载完成!");
		}
	</script>
</head>
<body>
	<h1>Hello World!</h1>
	<img src="image.jpg">
	<p>Some text...</p>
</body>
</html>

当页面加载完成后,会弹出一个提示框,显示页面已经加载完成。

如何获取 onload 事件中的数据?
<!DOCTYPE html>
<html>
<head>
	<title>Onload Data</title>
	<script>
		window.onload = function () {
			var h1Element = document.getElementsByTagName("h1")[0];
			var imgElement = document.getElementsByTagName("img")[0];
			alert("页面标题:" + h1Element.innerHTML + "\n图片地址:" + imgElement.src);
		}
	</script>
</head>
<body>
	<h1>标题</h1>
	<img src="image.jpg">
</body>
</html>

通过 document.getElementsByTagName() 方法来获取页面中的元素,我们可以在 onload 事件中获取到页面中的各种数据。

在 onload 事件中加载更多数据
<!DOCTYPE html>
<html>
<head>
	<title>Onload Event</title>
	<script>
		window.onload = function () {
			var xhr = new XMLHttpRequest();
			xhr.onreadystatechange = function() {
				if (this.readyState == 4 && this.status == 200) {
					document.getElementById("demo").innerHTML = this.responseText;
				}
			};
			xhr.open("GET", "data.txt", true);
			xhr.send();
		}
	</script>
</head>
<body>
	<h1>Hello World!</h1>
	<div id="demo"></div>
</body>
</html>

通过 XMLHttpRequest 对象,我们可以在 onload 事件中异步加载更多的数据。在上述代码中,我们通过 GET 请求获取到了一个名为 data.txt 的文件,并将其内容显示在了页面上。