【发布时间】:2014-03-07 21:31:27
【问题描述】:
我对下面的代码块有点困惑。我会在每一行旁边评论我认为的意思。如果有人可以帮助我澄清我的任何误解或确认我实际上解释正确,我将非常感激。
这是上下文中的代码:http://jsfiddle.net/MddHtt13/EMBZr/1/
if(!window.onload) { // If the window is not loaded then...
window.onload = function() { //Assign an anonymous function to the onload event
onLoad(); //Which, upon execution of the onload event execute the onLoad function
};
}
else { //This is probably the most confusing part
var oldWindowLoadFunction = window.onload; //Else if the window is loaded, assign the onload event to the variable oldWindowLoadFunction
window.onload = function() { //Then upon completion of the onload event, assign an anonymous function
oldWindowLoadFunction(); //which then re-executes the onload event
onLoad(); //and then executes the onLoad function
};
}
首先看不懂的是window.onload旁边的感叹号
if(!window.onload)
为什么我需要指定窗口是否尚未加载?我不是只想将 onLoad() 函数附加到 onload 事件,以便在完成后触发它吗?像这样说:
window.onload = onLoad();
为什么需要额外的步骤?为什么是 if/else 语句?
其次,为什么在代码块的后半部分我需要重新加载页面只是为了再次重新附加 onLoad() 函数?这让我回到了我刚刚问的问题。为什么它必须比简单的写作更复杂:
window.onload = onLoad();
当然,当我将代码更改为一个简单的语句时,就像上面的那个,它实际上不起作用。但是,我仍然没有完全理解有问题的代码块的每个部分的必要性。
如果有人能详细介绍我,那将非常有帮助。
编辑:
感谢以下人员的帮助,我用一个简单的语句替换了所有这些代码:
window.addEventListener('load', onLoad);
【问题讨论】:
-
仅供参考,没有理由在现代浏览器中使用这种复杂的附加 onload 处理程序的方法。只需使用
window.addEventListener("load", fn)将在现代浏览器中用更简单的代码完全取代它。 -
我知道这看起来太复杂了@jfriend00
标签: javascript