任务删除后恢复

Tasks restores after deletion

我添加了 3 个任务,例如“Task1”、“Task2”、“Task3”,然后删除了其中一个。按下回收站,任务将被删除,但是当我添加新任务“Task4”时,删除的任务也会被恢复。

我该如何解决?如果可能,请添加解释?

'use strict';

const headerInput = document.querySelector('.header-input');
const todoControl = document.querySelector('.todo-control');
const todoList = document.querySelector('.todo-list');
const todoCompleted = document.querySelector('.todo-completed');

const todoData = [];

const render = function() {
    todoList.textContent = '';
    todoCompleted.textContent = '';

    todoData.forEach(function(item){
        const li = document.createElement('li');
        li.classList.add('todo-item');
        li.innerHTML = '<span class="text-todo">' + item.value + '</span>' + 
                        '<div class="todo-buttons">' +
                            '<button class="todo-remove"></button>' +
                            '<button class="todo-complete"></button>' +
                        '</div>';

        if(item.completed){
            todoCompleted.append(li);
        } else {
            todoList.append(li);
        }

        const btnTodoCompleted = li.querySelector('.todo-complete');

        btnTodoCompleted.addEventListener('click', function(){
            item.completed = !item.completed;
            render();
        })

        const btnRemove = li.querySelector('.todo-remove');

        btnRemove.addEventListener('click', function(){
            li.remove();
        });
    });

};


todoControl.addEventListener('submit', function(event){
    event.preventDefault();

    const newTodo = {
        value: headerInput.value,
        completed: false
    };

    todoData.push(newTodo)

    render();
});

render();

创建新任务时,向数组中添加一条记录:

todoData.push(newTodo)

但是当你删除一个任务时,你并没有修改这个数组。您只需从页面中删除 <li> 元素:

li.remove();

因此下一次调用 render() 时,它将重新呈现数组中的列表,其中仍然包含“已删除”的记录。

不删除 <li> 元素,而是从数组中删除记录并重新调用 render():

btnRemove.addEventListener('click', function(){
    // re-assign the array to a filtered version of itself
    todoData = todoData.filter(function (i) {
        // only return records which don't match the current record
        return item.value !== i.value;
    });
    // re-render the list
    render();
});