javascript - 为什么 onload 事件没有按预期绑定(bind) `this` 变量?

标签 javascript web-services web-applications

有人知道为什么 onload 事件没有按预期绑定(bind) this 变量吗?

就像在这个测试脚本中一样,onkeydown 给我们 true (this 工作正常),但 onload 给我们 false (this 现在指向 window.. wth?):

<!DOCTYPE html>
<html><head>
<script>
function f(t){
alert(t===document.body);
}
</script>
</head><body onkeydown="f(this);" onload="f(this);">

</body></html>

最佳答案

请参阅documentation :

HTMLBodyElement.onload

Exposes the window.onload event handler to call when the window gains focus.

Note that this handler is triggered when the event reaches the window, not the body element. Use addEventListener() to attach an event listener to the body element.

重要的部分是当事件到达窗口时触发该处理程序。处理程序在 window 上下文中执行,而不是在 body 中执行。

FWIW,alert(window.onload === document.body.onload); 将产生 true

关于javascript - 为什么 onload 事件没有按预期绑定(bind) `this` 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6246600/

相关文章:

c# 将字符串作为代码执行

google-apps-script - 如何从谷歌应用程序脚本上的 "doPost"请求中获取源 URL

java - 如何进行 GWT 服务器调用(GWT RPC?)

带有开始/停止/重置和用户输入时间的javascript倒计时

javascript - 如何通过Enzyme获取依赖组件元素?

javascript - 如何使 Jquery-UI 按钮控件组突出显示所选项目?

c# - .NET 4.5 中的序列化中断

iphone - 如何通过Web服务(php)sql查询从ios iphone sdk中选择条件来捕获数据

java - Wicket调用冗长的操作并通过ajax更新

javascript - Express 模块不可用