想问下为什么这里会报错

大神们帮忙看看,

<!DOCTYPE html>
<html>
<head>

<title>测试</title>
<meta charset = "utf-8">
<style>
    div {width:150px;height:150px;display: inline-block;}
    .on {-webkit-animation:move 0.5s;}
    @-webkit-keyframes move {
          from{transform: rotate(0deg);}
          to {transform: rotate(60deg);}
    }
</style>

</head>
<body>

<div style = "background-color:red;"></div>
<div style = "background-color:green;"></div>
<div style = "background-color:blue;"></div>
<div style = "background-color:yellow;"></div>
<div style = "background-color:gray;"></div>

<script type="text/javascript">
    var divBox = document.getElementsByTagName("div");
    alert(divBox);
    for(var i = 0;i<divBox.length;i++){
          divBox[i].addEventListener("mouseover",function(){
                  if(divBox[i].classList.contains("on")==true){  //这个地方提示错误。。。。
                      this.classList.remove("on");
                  }else{
                      this.className = "on";
                  }
               
          })
    }
</script>

</body>
</html>

阅读 2.4k
4 个回答

classList.contains 本身不会报错,但是有兼容性要求。IE10+。
还有就是你那个判断根本不需要==true

if(this.classList.contains("on")==true)

在循环里面绑定事件,而且你绑定事件的处理方法使用了循环index的话,你需要在闭包里实现,不然index会变成循环结束时的index。搜索一下闭包。

 for(var i = 0;i<divBox.length;i++){
          divBox[i].addEventListener("mouseover",function(){
                  (function(i){
                      if(divBox[i].classList.contains("on")==true){  //这个地方提示错误。。。。
                          this.classList.remove("on");
                      }else{
                          this.className = "on";
                      }

                  })(i)               
          })
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题