如何使用保存按钮创建多个 todolist?

问题描述

下面是我的一些代码片段。想想关于类固醇的待办事项清单。我正在尝试创建多个 Div 元素,每次按下“保存”按钮时,这些元素都会保存到包含不同列表的页面。实际发生的是显示多个 div,但保存的原始 div 是唯一一个使用列表信息(就像在待办事项列表中,当你点击提交一个新的列表项时,我添加一个保存按钮和一个输入字段,用户可以使用它来命名他们的列表并将该列表保存到一个容器中,但只有一个 div 被更新) . 我知道我快到了,但我已经看了几个小时了,但不太明白。https://github.com/W33K5Y/TODO-PIRPLE

const saveButton = document.getElementById("submit-save");
const myLists = document.getElementById("my-lists");
const startNote = document.getElementById("start-note");
const listName = document.getElementById("new-list-name");
const myUl = document.getElementById("my-ul-lists");

// ! savebutton listener
saveButton.addEventListener("click",addNewTodo);
// ! make new html elements
const newTodoOl = document.createElement("ol");
const newTodoLi = document.createElement("li");
const listH1 = document.createElement("h4");

// ! =============== function for creating new todo ================================
function addNewTodo() {
  const todoDiv = document.querySelector(".todo-container");
  const todos = document.querySelectorAll(".todo-item");
  todos.forEach(function(todo) {
    createLi(todo);
  });
  listName.value ? listH1.innerText = listName.value : listH1.innerText = "My List";
  newTodoDivWrap.classList.add("new-todo-div");
  newTodoDivWrap.appendChild(listH1);
  newTodoDivWrap.appendChild(newTodoOl);
  myLists.appendChild(newTodoDivWrap);
  todoReset(todoDiv,startNote);
  startLoginSignUpNoneLobbyFlex();
}

// todo function to go in above that removes all of whats in the tido-container

function todoReset(div,lobbyDiv) {
  lobbyDiv.remove();
  div.firstElementChild.innerHTML = "";
}

function createLi(todo) {
  // ! Create LI
  const newTodo = document.createElement('li');
  newTodo.innerText = todo.innerText;
  newTodo.classList.add("todo-saved-item");
  newTodoOl.appendChild(newTodo);
}

解决方法

我认为以下是它无法按预期工作的原因:

const newTodoOl = document.createElement("ol");
const newTodoLi = document.createElement("li");
const listH1 = document.createElement("h4");

请记住,javascript 会创建引用,因此当您执行此类操作时—newTodoDivWrap.appendChild(listH1)—您不会添加新元素,而只会添加对所述元素的引用。

这就像你有两个对象一样。

var a = {'name': 'Anette'}
var bbbb = a // creates a reference,not a new object.
bbbb.name = 'Bjorn'

console.log(a.name) // Bjorn

因此在方法内部创建新元素,而不是创建和调用公共元素。


另外,这样的评论是不必要的:

function createLi(todo) {
  // ! Create LI

你有一个完美地解释了它的作用的方法名称。你不需要评论。开始养成命名变量或方法来解释发生了什么的习惯——你已经这样做了(例如 startLoginSignUpNoneLobbyFlex)——这样你就不必使用注释了。注释是无用的,除非用于文档。

,

你必须移动

const newTodoOl = document.createElement("ol");
const newTodoLi = document.createElement("li");
const listH1 = document.createElement("h4");

进入 addNewTodo 函数。这样每次迭代都会产生一个全新的 List
Rickard 为我指明了正确的方向 :)