關于直接將id屬性作為index使用
首先,我沒直接使用id作為索引,使用setAttribute方法避免直接使用id,前端工程師應該知道ID對一個元素的重要性,在此案例中,id也不具有語義化,因此強烈建議使用setAttribute("index",i)來設置屬性,通過getAttribute(index)來獲取屬性值;我的代碼如下:
//封裝獲取ID的方法 function?$(id){ return?typeof?id==='string'?document.getElementById(id):id; } window.onload?=?tab; function?tab(){ var?index?=?0; //?當前高亮頁簽的索引 var?timer?=?null; //初始化定時器 var?nav?=?$('tabMenu').getElementsByTagName('li'); //?獲取tab中的導航元素 var?con?=?$('tabContent').getElementsByTagName('div'); //?獲取tab中的內容 //如果nav數(shù)目和內容數(shù)目不等 if(nav.length?!=?con.length)?return; //綁定手動事件 for(var?i=0;i<nav.length;i++){ nav[i].setAttribute("order",i); nav[i].onmouseover?=?function(){ clearInterval(timer); changeOption(this.getAttribute('order')); //?alert(this.order); } //鼠標移入事件 nav[i].onmouseout=function(){?? ??timer=setInterval(autoPlay,1500);???? } //鼠標移出事件 } if(timer){ ??clearInterval(timer); ??timer=null; } //?添加定時器,改變高亮的頁簽 timer?=?setInterval(autoPlay,1500) //?封裝自動播放函數(shù) function?autoPlay(){ index++; if(index>=nav.length){ index?=?0; } changeOption(index); } //封裝重復的函數(shù) function?changeOption(curIndex){ for(var?j=0;j<nav.length;j++){ nav[j].className=""; con[j].style.display="none"; } nav[curIndex].className?=?"select"; con[curIndex].style.display?=?"block"; index?=?curIndex; } } //function?tab
2016-04-25
不錯,有自己的想法
2017-01-24
其實我也這么想的