我有两个js文件,每个文件都有自己的window.onload处理程序。根据我将两个onload处理程序附加到窗口对象的方式,我在第二个处理程序上得到了不同的行为。
更具体地说,这是我的html文件:
<html>
<head>
<title>Welcome to our site</title>
<script type="text/javascript" src="script1.js"> </script>
<script type="text/javascript" src="script2.js"> </script>
</head>
<body id="pageBody">
<h2 align="center">
<a href="http://www.whatever.com" id="redirect"> Wellcome to our site... c'mon in! </a>
</h2>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
它加载两个js文件,script1.js和script2.js。
这是这两个脚本的版本,它们导致(至少在我看来)意外的行为。
Script1.js:
window.onload = initAll1(); // attach first onload handler
function initAll1() {
alert("initAll1");
document.getElementById("redirect").onclick = foo; // attach an onclick handler
}
function foo() {
alert("we are in foo");
return false;
}
Run Code Online (Sandbox Code Playgroud)
Script2.js:
addOnloadHandler(initAll2); // with this we should attach a second onload handler …Run Code Online (Sandbox Code Playgroud)