1

如何在窗口的 onload 事件上调用多个 javascript 函数?

例如,

             window.onload=MyFunc(); //Single Function

但是,如果在窗口的 onload 事件上调用多个函数怎么办......

4

4 回答 4

11

把它们包起来。

window.onload = function() { MyFunc(); MyOtherFunc(); }
于 2010-11-02T06:54:06.973 回答
4

或者您可以将函数绑定到窗口的加载事件:

window.addEventListener("load", MyFunction, false);
window.addEventListener("load", MyOtherFunction, false);

对于 IE legacy,您可能需要使用 attachEvent 方法:

window.attachEvent("load", MyFunction);
window.attachEvent("load", MyOtherFunction);

这种方法的问题是无法计算函数执行的顺序。

于 2010-11-02T07:03:14.033 回答
1

这是一个示例,可以解释如何:

// create an array that will contain all 
// your functions that you would like to 
// call on page load
var pageOnLoadEvents = [];

// Add one or more functions in pageOnLoadEvents array
pageOnLoadEvents.push(function() { alert("Hello!"); })
pageOnLoadEvents.push(function() { alert("How are you?"); })


// This will call when your page will load
window.onload = function() {
  // Loop through each index of pageOnLoadEvents
  for(var index = 0; index < pageOnLoadEvents.length; index++) {
   // '()' brackets in the end tell them to make a call
   // If you don't include '()' at the end this will
   // suspect as a object as in JavaScript functions 
   // are first-class objects.
   // document.write(pageOnLoadEvents[index].toString()); // treat as object
   pageOnLoadEvents[index]();
  }
}

上面的示例试图简单地为您解释您的问题。然而,西蒙威利森的博客有一个很好的解释,他写道:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
addLoadEvent(function() {
  /* more code to run on page load */ 
});

addLoadEvent 函数将另一个函数作为参数,该函数应在页面加载后执行。与直接分配给 window.onload 不同,该函数以这样一种方式添加事件,即任何先前添加的 onload 函数都将首先执行。阅读更多

于 2010-11-02T11:56:58.603 回答
0

为什么不采用一种老派的方式在页面加载时调用的一个函数中调用尽可能多的函数呢?window.addEventListener("load", Foo, false);

其中 Foo 调用了所有必需的函数。这样,您可以在需要时控制顺序和返回值。

于 2010-11-02T10:32:08.483 回答