问题描述
- 在一个html中调用两个javascript为什么不能同时运行。。急!!
-
<script src="script01.js"></script> <script src="script02.js"></script>
这是script01.js
window.onload = choosePic; var adImages = new Array("images/3.jpg","images/2.jpg","images/113.jpg"); var thisAd = 0; function choosePic() { thisAd = Math.floor((Math.random() * adImages.length)); document.getElementById("adBanner").src = adImages[thisAd]; rotate(); } function rotate() { thisAd++; if (thisAd == adImages.length) { thisAd = 0; } document.getElementById("adBanner").src = adImages[thisAd]; setTimeout(rotate, 2 * 1000); }
这是script02.js
window.onload = initAll; function initAll() { var allLinks = document.getElementsByTagName("a"); for (var i=0; i<allLinks.length; i++) { if (allLinks[i].className.indexOf("menuLink") > -1) { allLinks[i].onclick = toggleMenu; } } } function toggleMenu() { var startMenu = this.href.lastIndexOf("/")+1; var stopMenu = this.href.lastIndexOf("."); var thisMenuName = this.href.substring(startMenu,stopMenu); var thisMenu = document.getElementById(thisMenuName).style; if (thisMenu.display == "block") { thisMenu.display = "none"; } else { thisMenu.display = "block"; } return false; }
解决方案
不要window.onload=xxx,这样只有最后倒入的window.onload有效,前面的会被覆盖,要使用attachEvent或者addEventListener来添加
function addEvent(o,evt,func){
if(o.attachEvent)o.attachEvent('on'+evt,func);
else if(o.addEventListener)o.addEventListener(evt,func,false);
}
/// window.onload = initAll;
addEvent(window,'load',initAll)
/// window.onload = choosePic;
addEvent(window,'load',choosePic)
解决方案二:
谢谢。。。终于可以运行了。。
时间: 2024-10-26 09:39:25