简体   繁体   English

"localStorage 无法正常工作\/localStorage 覆盖自身"

[英]localStorage not working properly/localStorage overwriting itself

I'm attempting to create a simple to-do list and I've encountered two problems:我正在尝试创建一个简单的待办事项列表,但遇到了两个问题:

  1. After refreshing the page, all the created elements are no longer visible on the page despite being in local storage.刷新页面后,所有创建的元素在页面上不再可见,尽管在本地存储中。
  2. After refreshing the page and submitting new values to the input, localStorage overwrites itself.刷新页面并向输入提交新值后, localStorage会覆盖自身。 Despite that, the items displayed from the input fields are from the previous localStorage , which no longer exists (I really hope this makes sense).尽管如此,输入字段中显示的项目来自以前的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 code below: 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刷新页面后,所有创建的元素在页面上不再可见,尽管在本地存储中

<\/blockquote>

That is because you are rendering the HTML only after the click event and not on page load<\/a> .那是因为您仅在单击事件之后而不是在页面加载<\/a>时才呈现 HTML。 To render the HTML for existing tasks stored in the localStorage<\/code> you have to write a code that loops over your existing tasks in the tasksItem<\/code> and applies the rendering logic to it.要为存储在localStorage<\/code>中的现有任务渲染 HTML,您必须编写一个代码,循环遍历tasksItem<\/code>中的现有任务并将渲染逻辑应用于它。

I would suggest splitting the rendering code from your createTask()<\/code> function and create a new function for it (for example renderTask()<\/code> ), then you can use it inside a loop on page load and also call the function once a new task is created in the createTask()<\/code> function.我建议从您的createTask()<\/code>函数中拆分渲染代码并为其创建一个新函数(例如renderTask()<\/code> ),然后您可以在页面加载的循环中使用它,并在创建新任务后调用该函数在createTask()<\/code>函数中。

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

After refreshing the page and submitting new values to the input, localStorage overwrites itself.刷新页面并向输入提交新值后,localStorage 会覆盖自身。

<\/blockquote>

That's because you are actually overriding the tasks in the localStorage<\/code> .那是因为您实际上覆盖了localStorage<\/code>中的任务。 To keep existing tasks, you have to use your tasksItem<\/code> variable instead of the blank tasks<\/code> array to create your tasks in and save them to the localStorage<\/code> .要保留现有任务,您必须使用您的tasksItem<\/code>变量而不是空白tasks<\/code>数组来创建您的任务并将它们保存到localStorage<\/code> 。

So, instead of:所以,而不是:

 tasks.push(inputEl.value)<\/code><\/pre>

You would use:你会使用:

 tasksItem.push(inputEl.value)<\/code><\/pre>

The same goes for:这同样适用于:

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

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

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