繁体   English   中英

点击事件监听器只工作一次而不刷新页面

[英]click event listener is only working once without refreshing the page

我正在构建一个待办事项应用程序,我的删除待办事项操作仅触发一次而不刷新页面。 每次单击按钮时,我的预期行为都会打开,它应该删除相应的项目

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);
  });
});

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

  1. 单独呈现您的按钮,不要在每次点击时重新创建它;

  2. 在每个渲染事件上向新创建的按钮添加事件侦听器。

最好使用第一种方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM