[英]How do I display every element from my localStorage item?
i'm trying to create a simple To-do list, and my question is how do i get all elements of a single item in localStorage displayed?我正在尝试创建一个简单的待办事项列表,我的问题是如何显示 localStorage 中单个项目的所有元素?
pushing things into localStorage in a form of an array works fine, but only thing I see on my page is the first index of the "tasks" array.以数组的形式将内容推入 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 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)
localStorage.setItem("tasks", JSON.stringify(tasks))
inputEl.value = ""
newParagraph.textContent = JSON.parse(localStorageContent)
errorMsg.textContent = ""
}else{
errorMsg.textContent = "You have to type something in!"
errorMsg.classList.toggle("visibility")
}
}
submitBtn.addEventListener("click", () =>{
createTask()
})
When you execute JSON.parse(localStorageContent)<\/strong> you convert your string into an array, that's right.当您执行JSON.parse(localStorageContent)<\/strong>时,您将字符串转换为数组,这是正确的。
But:但:
newParagraph.textContent = JSON.parse(localStorageContent)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.