【问题标题】:Problem with for loop in a to-do website - JavaScript待办事项网站中的 for 循环问题 - JavaScript
【发布时间】:2021-10-26 10:54:56
【问题描述】:

我在创建将删除所有待办事项列表的 for 循环时遇到问题。我已经编写了一个星期了,所以这听起来像是一个非常愚蠢的问题。代码全部在一个函数中,由按钮的 onclick 属性运行。

    let toDoList = document.querySelector(".to-do-list");
    let newListClass = document.getElementsByClassName('new-list');
    let newList = document.querySelector('.new-list');

    console.log(newList);
    console.log(newListClass.length);
    
    for (i = 0; i < newListClass.length; i++) {
        newList.remove();
    }

【问题讨论】:

  • 嗨!那么..它有什么问题?你有错误吗?另外,你到底想做什么?您的循环实际上没有意义,因为 newList 始终只是一个元素,这意味着您只能将其删除一次。
  • 它只删除其中一个列表,但我不知道如何循环,所以我创建的所有新列表都会被删除。

标签: javascript loops for-loop


【解决方案1】:

我看到的两个主要选项:

// Option A) getting elements by class name
const newListClass = document.getElementsByClassName('new-list');
console.log(newListClass);

for (i = 0; i < newListClass.length; i++) {
    newListClass[i].remove();
}

// Option B) getting elements with a selector, notice the "All"
const newListClass = document.querySelectorAll('.new-list');
console.log(newListClass);

for (i = 0; i < newListClass.length; i++) {
    newListClass[i].remove();
}

您也可以使用 forEach,但经典的 for 循环总是不错的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 2020-09-15
    • 1970-01-01
    • 2012-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多