Browser runtimes ignore non-object (string, number, true, false, undefined, null, NaN) values set to the DOM events such as window.onload. So if you write window.onload = 10 or any of the above mentioned value-types (including the hybrid string) the event will remain null.
What is more funny that the event handlers will get any object type values, even window.onload = new Date is a pretty valid code that will prompt the current date when you log the window.onload. :) But sure nothing will happen when the window.load event fires.
assigns the onload event to whatever is returned from the init function when it's executed. init will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned to window.onload. It's unlikely you'd ever want this, but the following would be valid:
function init() {
var world = "World!";
return function () {
alert("Hello " + world);
};
}
window.onload = init();
window.onload = init;
将onload事件分配给函数init。当onload事件触发时,将运行init函数。
function init() {
var world = "World!";
alert("Hello " + world);
}
window.onload = init;
好的答案,还有一件事要补充:
Browser runtimes ignore non-object (
string, number, true, false, undefined, null, NaN
) values set to the DOM events such as window.onload. So if you writewindow.onload
= 10 or any of the above mentioned value-types (including the hybridstring
) the event will remainnull
.What is more funny that the event handlers will get any object type values, even
window.onload = new Date
is a pretty valid code that will prompt the current date when you log thewindow.onload
. :) But sure nothing will happen when thewindow.load
event fires.因此,始终将函数分配给JavaScript中的任何事件。
assigns the onload event to whatever is returned from the init function when it's executed.
init
will be executed immediately, (like, now, not when the window is done loading) and the result will be assigned towindow.onload
. It's unlikely you'd ever want this, but the following would be valid:将onload事件分配给函数init。当onload事件触发时,将运行init函数。
将foo的值分配给窗口对象的onload属性。
将通过调用foo()返回的值分配给窗口对象的onload属性。该值是否来自return语句取决于foo,但是返回一个函数(需要return语句)是有意义的。
当发生load事件时,如果window.onload的值是函数引用,则window的事件处理程序将对其进行调用。