javascript - 简单的 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... ?
解决方案
您不应该使用索引,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>
推荐阅读
- web-scraping - 即使在使用 selenium 自动滚动后也无法抓取所有照片
- javascript - 如何访问嵌套对象值
- javascript - How to catch the exception in the right way? [beginner]
- python - how display contexts of two different app and different view in one template in one project in django?
- python-3.x - NameError on a function while calling for it in another function of a class
- java - “java.lang.IllegalStateException:测试上下文的 WebApplicationContext [...] 必须使用 MockServletContext 进行配置。”
- azure - 将 Python API 部署到 Azure 应用服务
- c# - 我有一个将字符分配给 char 数组的 for 循环,错误:System.IndexOutOfRangeException
- aurelia - 通过 HTML 循环在 Aurelia 中每行有一个项目的表格和一些属性
- python - boto3:generate_presigned_url 在上传期间被拒绝访问