问答详情
源自:-

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);

   });


提问者:Emily梦 2017-03-17 14:53

个回答

  • yingql
    2017-03-19 22:33:12
    已采纳

    这个是关于for循环里的闭包的知识,你打印一下就会发现每次执行的时候i的值都是as.length,所以会报错。帮你找了篇文章,简单看一下就知道原因了。