简体   繁体   English

为什么window.onload工作而document.onload不工作?

[英]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.onloaddocument.onload一个或另一个分配了一个函数):

  1. window.onload === onload
  2. window.onload !== document.onload
  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM