有人知道为什么 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/