首页 > 解决方案 > 简单的 js forloop 只迭代一次

问题描述

我有一个 JS for 循环,它遍历具有特定类的所有元素,然后删除该类。然而,当循环对找到的第一个元素起作用时,它会停止。我看不到任何错误,我已经在 try/catch 中尝试过,但看不到任何其他可能导致问题的东西。有没有人有什么建议?谢谢 :)

let visibleTags = document.getElementsByClassName('show');
console.log(visibleTags.length) // length is 2

for (let index = 0; index < visibleTags.length; index++) {
   console.log(index); // 0
   visibleTags[index].classList.remove('show'); // removes 'show' from element 0
}

// element 1 still has the 'show' class and was not touched by the loop... ?

标签: javascriptfor-loop

解决方案


您不应该使用索引,visibleTag它是一个实时集合,并且您正在修改部分选择标准(show类),因此集合本身会发生变化。由于您想show从具有show该类的所有内容中删除,因此使用这样的while循环会更好:

let shown = document.getElementsByClassName('show');
while(shown.length > 0) {
  shown[0].classList.remove('show');
}
<div>
  <div class="show">1</div>
  <div class="show">2</div>
  <div class="show">3</div>
  <div class="show">4</div>
</div>


推荐阅读