localStorage 不工作 properly/localStorage 覆盖自身

localStorage not working properly/localStorage overwriting itself

我正在尝试创建一个简单的待办事项列表,但遇到了两个问题:

  1. 刷新页面后,尽管在本地存储中,所有创建的元素都不再显示在页面上。
  2. 刷新页面并向输入提交新值后,localStorage 会自行覆盖。 尽管如此,输入字段中显示的项目来自以前的 localStorage,它不再存在(我真的希望这是有意义的)。
const inputEl = document.getElementById("inputEl")
const submitBtn = document.getElementById("submit")
const clearBtn = document.getElementById("clearBtn")
const todoListContainer = document.getElementById("todoList")
const taskContainer = document.querySelector(".task")
const cancelBtn = document.querySelector(".cancelBtn")
const doneBtn = document.querySelector(".doneBtn")
const errorMsg = document.querySelector(".error")

let localStorageContent = localStorage.getItem("tasks")
let tasksItem = JSON.parse(localStorageContent)
let tasks = []

function createTask() {
    if (inputEl.value.length != 0) {


        const newDiv = document.createElement("div")
        newDiv.classList.add("task")
        const newParagraph = document.createElement("p")
        const newCancelBtn = document.createElement("button")
        newCancelBtn.classList.add("cancelBtn")
        newCancelBtn.textContent = "X"
        const newDoneBtn = document.createElement("button")
        newDoneBtn.classList.add("doneBtn")
        newDoneBtn.textContent = "Done"

        todoListContainer.appendChild(newDiv)
        newDiv.appendChild(newParagraph)
        newDiv.appendChild(newCancelBtn)
        newDiv.appendChild(newDoneBtn)
        //^^ Creating a container for a new task, with all its elements and assigning the classes^^



        tasks.push(inputEl.value)
        inputEl.value = ""

        for (let i = 0; i < tasks.length; i++) {
            localStorage.setItem("tasks", JSON.stringify(tasks))
            newParagraph.textContent = JSON.parse(localStorageContent)[i]
        }

        errorMsg.textContent = ""

    } else {
        errorMsg.textContent = "You have to type something in!"
        errorMsg.classList.toggle("visibility")

    }

}

submitBtn.addEventListener("click", () => {
    createTask()
})

clearBtn.addEventListener("click", () => {
    localStorage.clear()
})

HTML 代码如下:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/style.css">
      <script src="/script.js" defer></script>
      <title>To-do list</title>
   </head>
   <body>
      <h2 class="error visibility"></h2>
      <div id="todoList">
         <h1>To-Do List</h1>
         <input type="text" name="" id="inputEl" placeholder="Add an item!">
         <button type="submitBtn" id="submit">Submit</button>
         <button id="clearBtn">Clear list</button>
         <div class="task">
         </div>
      </div>
   </body>
</html>

After refreshing the page, all the created elements are no longer visible on the page despite being in local storage

那是因为您只在单击事件之后而不是在 page load 上渲染 HTML。要为存储在 localStorage 中的现有任务呈现 HTML,您必须编写一个代码来循环遍历 tasksItem 中的现有任务,并将呈现逻辑应用于它。

我建议将呈现代码从您的 createTask() 函数中分离出来并为其创建一个新函数(例如 renderTask()),然后您可以在页面加载时在循环中使用它,并且在 createTask() 函数中创建新任务后调用该函数。

window.addEventListener('load', (event) => {
  // Your read, loop and render logic goes here
})

After refreshing the page and submitting new values to the input, localStorage overwrites itself.

那是因为您实际上覆盖了 localStorage 中的任务。要保留现有任务,您必须使用 tasksItem 变量而不是空白 tasks 数组来创建您的任务并将它们保存到 localStorage.

所以,而不是:

tasks.push(inputEl.value)

您将使用:

tasksItem.push(inputEl.value)

同样适用于:

for (let i = 0; i < tasksItem.length; i++) {
    localStorage.setItem("tasks", JSON.stringify(tasksItem))
    // …
}