我可以存储在 LOCAL STORAGE 中,但刷新页面后列表仍然消失了? Javascript 的基本待办事项列表应用

I can store in LOCAL STORAGE but the lists are still gone after refreshing the page? basic Todo list app with Javascript

我有一个 JavaScript 待办事项列表练习应用程序,我花了几个小时研究如何将它存储在本地存储中并且它可以工作。

但它并没有出现在待办事项列表的实际 HTML 页面中?我已经通过从 (localStorage.getItem & JSON.parse) 加载它看到了一些答案,但在我的情况下它仍然不起作用。

const add = document.getElementById("additem")
const remove = document.getElementById("removeitem")
const input = document.getElementById("inputBlank")
const contain = document.getElementById("container")

const LOCAL_STORAGE_PREFIX = "TODO_APP_V1"
const TODOS_STORAGE_KEY = `${LOCAL_STORAGE_PREFIX}- todos`
const todos = loadTodos() // Load from local storage


/// Appending all
add.addEventListener('click', function () {
    let btn = document.createElement('button');
    let paragraph = document.createElement("th");
    btn.innerText="x";
    btn.style.background="";
    paragraph.innerText = input.value;
    if (input.value === "") return
    todos.push(paragraph.innerText) <---
    input.value = "";
    paragraph.appendChild(btn);
    contain.appendChild(paragraph)
    saveTodos() <---

    todos.push(paragraph.innerText)
    btn.addEventListener('click', function () {
        contain.removeChild(paragraph)
    })
    remove.addEventListener('click', function () {
        contain.removeChild(paragraph);

    })

})

///Saving to local storage
function saveTodos() {
    localStorage.setItem(TODOS_STORAGE_KEY, JSON.stringify(todos))
}

//Getting from local storage
function loadTodos() {
    const todos = localStorage.getItem(TODOS_STORAGE_KEY)
    return JSON.parse(todos) || []
}

您没有告诉您的应用程序在页面刷新时显示检索到的待办事项数据。

在每次刷新页面时,您需要从 localStorage 检索您的待办事项数据(您已经完成),并循环遍历数组以显示数据。

您必须在 todos 变量下使用此代码(检索完成时)

todos.forEach((element) => {
  let paragraph = document.createElement("th");
  paragraph.innerText = element;
  let btn = document.createElement("button");
  btn.innerText = "x";
  paragraph.appendChild(btn);
  contain.appendChild(paragraph);
});

如果你能防止默认的点击行为,那就太好了。不然点击每一项都会刷新浏览器,看起来不太好看

刷新后需要重新渲染数据!

function loadTodos() {
    const todos = localStorage.getItem(TODOS_STORAGE_KEY)
    
    todos.forEach(function (element) {
        let btn = document.createElement('button');
        let paragraph = document.createElement("th");
        btn.innerText="x";
        btn.style.background="";
        paragraph.innerText = element;

        btn.addEventListener('click', function () {
            contain.removeChild(paragraph)
        })

        paragraph.appendChild(btn);
        contain.appendChild(paragraph);
    })

    return JSON.parse(todos) || []
}