window.onload = function(){
var para =document.createElement("p");
var info = "NodeName:";
info += para.nodeName;
info += " NodeType:";
info += para.nodeType;
alert(info);
}
window.onload = function(){
var para = document.getElementById("testid");
var e = document.createElement("p");
var txt = document.createTextNode("hello zmz");
para.appendChild(e);
e.appendChild(txt);
}
Only the second window.onload is executed, but I want both window.onload to be executed. What to do?
We all know that the onload event can only be executed once, so assuming that you want to run two functions executed during onload, and finally only the function of the latter onload event can be executed, then how do we execute the functions of multiple onload events? The form is as follows :
window.onload = function(){
num1();
num2();
}
So, let’s add a function addLoadEvent(func), which only accepts parameters, which is the name of the function that is executed when the page is loaded
function addLoadEvent(func){
var oldonload = window.onload; //把現(xiàn)在有window.onload事件處理函數(shù)的值存入變量oldonload。
if(typeof window.onload != 'function'){ //如果這個處理函數(shù)還沒有綁定任何函數(shù),就像平時那樣把新函數(shù)添加給它
window.onload = func;
}else{ //如果在這個處理函數(shù)上已經(jīng)綁定了一些函數(shù)。就把新函數(shù)追加到現(xiàn)有指令的末尾
window.onload = function(){
oldonload();
func();
}
}
}
Call:
addLoadEvent(num1);
addLoadEvent(num2);
window.addEventListener('load',function(e){state1},false);
window.addEventListener('load',function(e){state2},false);
不建議用onload
It is recommended that one page be usedwindow.onload
window.onload = function(){
var para =document.createElement("p");
var info = "NodeName:";
info += para.nodeName;
info += " NodeType:";
info += para.nodeType;
alert(info);
var para = document.getElementById("testid");
var e = document.createElement("p");
var txt = document.createTextNode("hello zmz");
para.appendChild(e);
e.appendChild(txt);
}
If you are afraid of naming conflicts, you can use a closed space
window.onload = function(){
(function(){
var para =document.createElement("p");
var info = "NodeName:";
info += para.nodeName;
info += " NodeType:";
info += para.nodeType;
alert(info);
})();
(function(){
var para = document.getElementById("testid");
var e = document.createElement("p");
var txt = document.createTextNode("hello zmz");
para.appendChild(e);
e.appendChild(txt);
})();
}
Method 1
function fn1(){
var para =document.createElement("p");
var info = "NodeName:";
info += para.nodeName;
info += " NodeType:";
info += para.nodeType;
alert(info);
}
function fn2(){
var para = document.getElementById("testid");
var e = document.createElement("p");
var txt = document.createTextNode("hello zmz");
para.appendChild(e);
e.appendChild(txt);
}
window.onload = function(){
fn1();
fn2();
}
Method 2 is to use the method upstairs.
window.addEventListener('load',function(e){fn1();},false);
window.addEventListener('load',function(e){fn2();},false);