[英]Why does window.onload work while document.onload doesn't?
Can anyone tell me why the following page doesn't trigger an alert when it loads? 任何人都可以告诉我为什么下一页加载时不会触发警报? If I use
window.onload
instead of document.onload
it works. 如果我使用
window.onload
而不是document.onload
它可以工作。 Why is there this difference? 为什么会出现这种差异?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
document.onload = function() {
alert('Test');
}
</script>
</head>
<body>
</body>
</html>
The simplest answer is that it just wasn't designed that way. 最简单的答案是它不是那样设计的。 The browser executes the function attached to
window.onload
at the " end of the document loading process ". 浏览器在“ 文档加载过程结束时 ”执行附加到
window.onload
的功能。 It does not attempt to execute a function attached to document.onload
. 它不会尝试执行附加到
document.onload
的函数。
You could assign a function to document.onload
but the browser will not do anything special with it. 您可以为
document.onload
分配一个函数,但浏览器不会对它做任何特殊操作。
Some things to keep in mind (assuming you've just assigned a function to one or the other of window.onload
or document.onload
): 要注意的一些事项(假设您刚刚为
window.onload
或document.onload
一个或另一个分配了一个函数):
window.onload === onload
window.onload !== document.onload
window !== document
The event handler is onload
not document.onload
. 事件处理程序是
onload
而不是document.onload
。 It hangs directly off the window
object (which is the default object). 它直接挂在
window
对象(这是默认对象)之外。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.