Javascript 单击事件侦听器仅工作一次,而不刷新页面

Javascript 单击事件侦听器仅工作一次,而不刷新页面,javascript,Javascript,我正在构建一个todo应用程序,我的删除todo操作只会触发一次,而不会刷新页面。我的预期行为是,每次单击按钮时,它都会删除相应的项 const setTodos = (todos) => { localStorage.setItem("todos", JSON.stringify(todos)); console.log("todos saved", todos.length + 1); }; const getTodos = () =&

我正在构建一个todo应用程序,我的删除todo操作只会触发一次,而不会刷新页面。我的预期行为是,每次单击按钮时,它都会删除相应的项

const setTodos = (todos) => {
  localStorage.setItem("todos", JSON.stringify(todos));
  console.log("todos saved", todos.length + 1);
};

const getTodos = () => {
  const todos = localStorage.getItem("todos");
  return JSON.parse(todos);
};

const todos = getTodos() === null ? [] : getTodos();

// Render todos
const renderTodos = (todos) => {
  const todoWrapper = document.querySelector("#todo-list-wrapper");
  todoWrapper.innerHTML = "";
  const todoListWrapper = document.createElement("ul");
  todoWrapper.appendChild(todoListWrapper);
  todos.forEach((todo) => {
    const todoItem = document.createElement("li");
    todoItem.textContent = todo.title;
    todoListWrapper.appendChild(todoItem);

    const checkBox = document.createElement("input");
    checkBox.name = "todoMarkDone";
    checkBox.type = "checkbox";
    checkBox.checked = todo.completed;
    checkBox.id = todo.id;
    todoItem.prepend(checkBox);

    const button = document.createElement("button");
    button.name = todo.id;
    button.className = "delete-button";
    button.textContent = "delete";
    todoItem.appendChild(button);
  });
};
renderTodos(todos);


// Delete Todos
const buttons = document.querySelectorAll(".delete-button");
buttons.forEach(function (button) {
  button.addEventListener("click", function (e) {
    const filteredTodos = todos.filter((todo) => todo.id !== e.target.name);
    setTodos(filteredTodos);
    renderTodos(filteredTodos);
  });
});

出现此问题是因为在渲染代码中重新创建了一个按钮。有两种解决方法:

  • 单独渲染按钮,不要每次单击都重新创建按钮

  • 将事件侦听器添加到每个渲染事件上新创建的按钮


  • 最好使用第一种方法。

    很抱歉,这是一个错误在
    renderdos
    中添加事件侦听器-因为您调用该函数来重新呈现TODO,所以在您第二次调用
    renderdos
    时不会添加事件侦听器-或者,不是每次删除TODO时都重新呈现所有TODO,只需从DOM
    e.target.parentElement.remove()中删除单击的todo
    只需删除删除的
    todo
    是最好的方法:p