as[i].style.background="#fcc“為什么會報錯呢?代碼中下劃線部分,和作用域有關嗎
for(i=0,j=as.length;i<j;i++){
? ?//for (i in as){//用for in不行嗎,會打出prototype
? ? ? eventUtil.addEvent(as[i],"mouseover",function(){
? ? ? ? resetIndex();
? ? ? ? //用as[i]不行嗎
? ? ? ? this.style.background="#fcc";
? ? ? ? //as[i].style.background="#fcc";//Uncaught TypeError: Cannot set property 'background' of undefined at HTMLAnchorElement.<anonymous>?
? ? ? });
? ? ? eventUtil.addEvent(as[i],"mouseout",function(){
? ? ? ? this.style.background="#fff";
? ? ? });
? ? ? eventUtil.addEvent(as[i],"click",function(){
? ? ? ? console.log(mouseIndex);
? ? ? ? title.innerHTML=this.innerHTML;
? ? ? })
? ?}
? ?eventUtil.addEvent(document,"click",function(){
? ? ?menu.style.display="none";
? ? ?//eventUtil.stopPropagation(document);
? ?});
? ?eventUtil.addEvent(title,"click",function(e){
? ? ?menu.style.display="block";
? ? ?eventUtil.stopPropagation(e);
? ?});
2017-03-19
這個是關于for循環里的閉包的知識,你打印一下就會發現每次執行的時候i的值都是as.length,所以會報錯。幫你找了篇文章,簡單看一下就知道原因了。