-
-
Save HereChen/d99ec2f35f826ffd1f21 to your computer and use it in GitHub Desktop.
Javascript : window.onload 绑定多个事件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*假设有2个函数firstFunction和secondFunction需要在网页加载完毕时执行, 需要绑定到window。onload。如果通过: | |
* | |
* window.onload = firstFunction; | |
* window.onload = secondFunction; | |
* 结果是只有secondFunction会执行,secondFunction会覆盖firstFunction。 | |
*/ | |
/* | |
*正确的方式是: | |
* Javascript 共享onload事件处理方法: | |
*/ | |
//1.在需要绑定的函数不是很多时,可以创建一个匿名函数容纳需绑定的函数,再将该匿名函数绑定至window。onload函数 | |
window.onload = function() | |
{ | |
firstFunction(); | |
secondFunction(); | |
} | |
//2.实现一个函数addLoadEvent,如下 | |
function addLoadEvent(func) | |
{ | |
var oldOnLoad = window.onload; | |
if(typeof window.onload != 'function') | |
{ | |
window.onload = func; | |
} | |
else | |
{ | |
window.onload = function() | |
{ | |
oldOnLoad(); | |
func(); | |
} | |
} | |
} | |
addLoadEvent(firstFunction); | |
addLoadEvent(secondFunction); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment