window.onload函数用法
平时做项目 经常需要使用window.onload,
但window.onload 不能同时加载多个函数。
比如;
- function t(){
- alert("t")
- }
- function b(){
- alert("b")
- }
- window.onload =t ;
- window.onload =b ;
- function t(){
- alert("t")
- }
- function b(){
- alert("b")
- }
- window.onload =t ;
- window.onload =b ;
function t(){
alert("t")
}
function b(){
alert("b")
}
window.onload =t ;
window.onload =b ;
后面会把前面的覆盖。
上面代码只会输出 b ;
解决方法:
程序代码
- window.onload =function() { t(); b(); }
- window.onload =function() { t(); b(); }
window.onload =function() { t(); b(); }
今天看书的时候学了一个函数,分享给大家:
程序代码
- function addLoadEvent(func) {
- var oldonload = window.onload;
- if (typeof window.onload != 'function') {
- window.onload = func;
- } else {
- window.onload = function() {
- oldonload();
- func();
- }
- }
- }
- function addLoadEvent(func) {
- var oldonload = window.onload;
- if (typeof window.onload != 'function') {
- window.onload = func;
- } else {
- window.onload = function() {
- oldonload();
- func();
- }
- }
- }
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
具体用法;
程序代码
- function t(){
- alert("t")
- }
- function b(){
- alert("b")
- }
- function c(){
- alert("c")
- }
- function addLoadEvent(func) {
- var oldonload = window.onload;
- if (typeof window.onload != 'function') {
- window.onload = func;
- } else {
- window.onload = function() {
- oldonload();
- func();
- }
- }
- }
- addLoadEvent(t);
- addLoadEvent(b);
- addLoadEvent(c);
- function t(){
- alert("t")
- }
- function b(){
- alert("b")
- }
- function c(){
- alert("c")
- }
- function addLoadEvent(func) {
- var oldonload = window.onload;
- if (typeof window.onload != 'function') {
- window.onload = func;
- } else {
- window.onload = function() {
- oldonload();
- func();
- }
- }
- }
- addLoadEvent(t);
- addLoadEvent(b);
- addLoadEvent(c);
function t(){
alert("t")
}
function b(){
alert("b")
}
function c(){
alert("c")
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
addLoadEvent(t);
addLoadEvent(b);
addLoadEvent(c);
//等价于 window.onload =function() { t(); b(); c() ;}