为什么这个classList会显示错误

时间:2018-03-08 07:28:31

标签: javascript

<!DOCTYPE html>
    <html>
    <head>
        <title>To-Do</title>
    <link rel="stylesheet" type="text/css" href="todos.css">
    </head>
    <body>
    <ul>
        <li><span>X</span> Do Programming</li>
        <li><span>X</span> Do More Programming</li>
        <li><span>X</span> Do more and more Programming</li>
    </ul>
    <script type="text/javascript" src="todos.js"></script>
    </body>
    </html>

CSS

.toggleli {
text-decoration: line-through;
color: grey;

}

的Javascript

var li = document.querySelectorAll("li");

for(i=0; i < li.length; i++) {
li[i].addEventListener("click", function() { 
    li[i].classList.toggle("toggleli");
});
}

这是错误

todos.js:5 Uncaught TypeError: Cannot read property 'classList' of undefined
    at HTMLLIElement.<anonymous>

但是当我改变了 li[i].classList.toggle("toggleli");this.classList.toggle("toggleli"); 错误消失了。问题是什么 li[i].classList and li.classList 在for循环中,因为在for循环之外它没有显示错误,但是我必须切换所有的li,所以我必须把它放在循环中

1 个答案:

答案 0 :(得分:0)

在点击事件

中使用this代替li[i]

var li = document.querySelectorAll("li");

for (i = 0; i < li.length; i++) {
  li[i].addEventListener("click", function() {
    this.classList.toggle("toggleli");
  });
}
.toggleli {
  text-decoration: line-through;
  color: grey;
}
<ul>
  <li><span>X</span> Do Programming</li>
  <li><span>X</span> Do More Programming</li>
  <li><span>X</span> Do more and more Programming</li>
</ul>