遍历div时"Cannot read property 'classList' of undefined"错误 - Javascript



我正在尝试在页面上切换 5 个圆圈(带有类"圆圈"的div(,以便在使用 eventListener 单击时更改背景颜色。

JavaScript:

var circle = document.querySelectorAll(".circle");
for(var i = 0; i < circle.length; i++){
 circle[i].addEventListener('click', function(){
 circle[i].classList.toggle('effect');
});
}

我不断收到错误"无法读取未定义的属性'classList'" - 我不确定为什么圆是未定义的?

.css:

.circle {
width: 100px;
height: 100px;
border: solid 3px black;
border-radius: 100%;
float: left;
margin: 1%;
}

.effect {
background-color: green;
border-color: blue;
}

.html:

 <!DOCTYPE html>
  <html>
  <head>
   <meta charset="utf-8">
   <title></title>
   <link rel="stylesheet" href="style.css">
 </head>
 <body>
  <div class="circle">
  </div>
  <div class="circle">
  </div>

  <div class="circle">
  </div>
  <div class="circle">
  </div>
  <div class="circle">
  </div>

 <script src="script.js"></script>
</body>
</html>

你传递给addEventListener的回调捕获循环中的变量i,所以当需要执行回调时(触发click事件(,回调只看到循环结束时的变量 i,这是你的circle.length,所以circle[i]将超出界限,返回一个不存在的元素(或undefined(。因此,要使其正常工作,请将背面的circle[i]更改为指向当前 DOM 元素的this,如下所示

for(var i = 0; i < circle.length; i++) {
     circle[i].addEventListener('click', function(){
         this.classList.toggle('effect');
});

了解更多有关此的信息 这里

由于click事件将在未来发生,但要更新的最后一个值作为循环i不会等待执行。

var circle = document.querySelectorAll(".circle");
for (var i = 0; i < circle.length; i++) {
  // Creating a closure & passing value of i which is received in argument x
  (function(x) {
    // adding the click event to the the element 
    circle[x].addEventListener('click', function() {
      // this will refer to the current element in target
      this.classList.toggle('effect')
    })
  }(i)) // passing the value of i
}

演示

最新更新