function $(id){ return typeof id === "string"?document.getElementById(id):id; } var timer = null; var index = 0; window.onload = tab; //这两行放外面会报错, //Uncaught TypeError: Cannot read property 'getElementsByTagName' of null tab.js:13 //Uncaught TypeError: Cannot read property 'length' of undefined var titles = $('notice-title').getElementsByTagName('li'); var divs = $('notice-con').getElementsByTagName('div'); function tab(){ //手动切换 for (var i = 0; i < titles.length; i++) { titles[i].id = i; titles[i].onmouseover = function(){ clearInterval(timer); // for (var j = 0; j < titles.length; j++) { // titles[j].className = ""; // divs[j].style.display = "none"; // }; // this.className = "select"; // divs[this.id].style.display = "block"; changeIndex(this.id); } titles[i].onmouseout = function(){ clearInterval(timer); timer = setInterval(changeTab,2000); } }; //自动切换页切 timer = setInterval(changeTab,2000); // 定义好的changeTab函数 function changeTab(){ // var titles = $('notice-title').getElementsByTagName('li'); // var divs = $('notice-con').getElementsByTagName('div'); index++; if(index>=titles.length){ index = 0; } // 其他样式去掉高亮 changeIndex(index); } function changeIndex(curIndex){ for (var i = 0; i < titles.length; i++) { titles[i].className = ""; divs[i].style.display = "none"; }; //高亮显示标签 titles[curIndex].className = "select"; divs[curIndex].style.display = "block"; } }
页面没加载完是找不到dom元素的,window.onload是等待页面dom和其他资源都加载后再执行dom查找。