清空后数组长度不会增加,并且无法在 HTMLCollection 上添加鼠标事件

Array length won't increment after being emptied and can't add a mouse event on an HTMLCollection

我想在 JavaScript 和 HTML 中创建自己的 grocery/task 列表。我可以向列表中添加内容没问题,但我有两个问题:

  1. 如果我将项目添加到列表中,然后按 "clear" 按钮删除列表中的所有内容,就可以了。但是,当我在清除列表后将其添加回列表时,我的控制台通知我我的数组仍然是空的,尽管屏幕上显示了新任务。
  2. 我的第二个问题更大。看,我所有的任务都在我认为是数组的地方,但实际上是一个 HTML 集合。所以,当我尝试设置一个 onclick 事件时,它不会 运行。我不知道为什么,我尝试使用以下问题:Removing HTMLCollection elements from the DOM 。它没有用。我尝试使用 itemHTMLCollection item() Method。没用。我最后的尝试是使用 for(let thing of... 但仍然没有结果。

这是我的代码:

let listGro = document.getElementById("list");

let aButton = document.getElementById("add");
let cButton = document.getElementById("clear");
let tasks = document.getElementsByTagName("li");


aButton.onclick = function addItem() {
    let newThing = prompt("What do you want to add?"); // asking what the person wants

    if (newThing) { // checking if the user actually added something
        let newItemList = document.createElement("li"); //create item list
        newItemList.className = "item";
        let newItemListText = document.createTextNode(newThing); // create text
        newItemList.appendChild(newItemListText); // append text
        listGro.appendChild(newItemList); // append new element
        console.log(`New task added\nNumber of tasks in the list: ${tasks.length}`);
    } else {
        alert("You can't add nothing");
    }

};

cButton.onclick = function clearList() {
    var conf = confirm("Are you sure you want to clear the list?");
    if (conf && tasks.length != 0) {
        for (let i = 0; i < tasks.length; i++) {
            tasks[i].style.display = "none";
        }
        tasks = [];
    }

}

for(let thing of tasks) {
    //tasks[i].onclick = function removeOrEditItem() {
        /*let demand = prompt("Do you want to edit or remove the item?\nPlease answer with 'edit' or 'remove'\nIf this is a mistake, just enter nothing.");
        if (demand === "edit") {
            let editItem = prompt("What is your new thing?");
            tasks[i].innerHTML = editItem;
        } else if (demand === "remove") {
            tasks[i].splice(i, 1);
        }
        console.log("clicked");
    };*/
    
    // The thing above was a previous attempt with for(let i; i< items.length... you can work with that or below.
    thing.onclick = function removeTask() {
        thing.style.display = "none";
        console.log("removed");
    }
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Website template</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
    </head>
    <body>
        <h1>Grocery lists manager</h1>
        <h2>Welcome! here you can manage your grocery list!</h2>
        <ul id = "list"><span>List:</span></ul>
        <button id = "add">Add</button>
        <button id = "clear">Clear list</button>
    </body>
    <script src = "script.js"></script>
</html>

任务列表在您清除后仍为空,因为您正在用空数组覆盖 HTML 集合。您将 document.getElementsByTagName("li"); 分配给 tasks,这是一个实时集合。将 [] 重新分配给它会给它一个非活动的空数组。与其使用 tasks[i].style.display="none 在视觉上隐藏任务并手动重置 tasks 集合,不如从 DOM 中删除每个任务元素并让您的实时集合自动更新。

从 DOM 中删除一个集合有一些缺陷,但通常可以通过以下方式完成:

while(tasks.length > 0) {
    tasks[0].parentNode.removeChild(tasks[0]);
}

您的事件侦听器未被添加,因为添加它们的代码仅在加载脚本时运行一次。当然,在加载脚本的实例中,列表中没有任何任务。首次添加时将事件侦听器添加到个人newItemList

确保从 DOM 中删除任务,而不只是隐藏它。

 newItemList.onclick = function removeTask() {
     newItemList.parentNode.removeChild(newItemList);
     console.log("removed");
 }

您完整的 JavaScript 可能如下所示:

let listGro = document.getElementById("list");
let aButton = document.getElementById("add");
let cButton = document.getElementById("clear");
let tasks = document.getElementsByTagName("li");

aButton.onclick = function addItem() {
    let newThing = prompt("What do you want to add?"); // asking what the person wants

    if (newThing) { // checking if the user actually added something
        let newItemList = document.createElement("li"); //create item list
        newItemList.className = "item";
        let newItemListText = document.createTextNode(newThing); // create text
        newItemList.appendChild(newItemListText); // append text
        newItemList.onclick = function removeTask() {
            newItemList.parentNode.removeChild(newItemList);
            console.log("removed");
        }
        listGro.appendChild(newItemList); // append new element
        console.log(`New task added\nNumber of tasks in the list: ${tasks.length}`);
    } else {
        alert("You can't add nothing");
    }
};

cButton.onclick = function clearList() {
    var conf = confirm("Are you sure you want to clear the list?");
    if (conf && tasks.length != 0) {
        while(tasks.length > 0) {
            tasks[0].parentNode.removeChild(tasks[0]);
        }
    }
};