本地存储无法存储创建的任务列表

Local storage not working to store created Task List

我在两个函数中创建了本地存储,一个函数使用存储密钥设置本地存储,第二个函数获取存储密钥,但它不起作用。

我将本地存储函数与 createTask 函数绑定在一起,因为这是创建任务的地方。

结果应该是本地存储保存了浏览器刷新时用户创建的任务列表,我想在这种情况下使用本地存储。

JS代码

const STORAGE_KEY = "task-list-storage-key";

/**********************************************
 * function that creates the HTML elements    *
 **********************************************/

 const createTask = () => {
    const id = createId()
    const task = elements.input.value;
    const date = elements.cal.value;

    if(!task && !date) return alert("Please fill in task and select date");
    if(!task) return alert("Please fill in task");
    if(!date) return alert("Please select date");

    const tasks = document.createElement("div");

    tasks.innerHTML = `
    <button class = "sort">Sort</button>
    <div class="task" data-id = "${id}">
        <div class="content">
            <input type ="checkbox" class="tick">
            <input type ="text" class = "text" id = "text" value="${task}" readonly>
            <label class = "due-date" for ="text">${date}</label>
            <input type ="date" class = "date" id = "date">
        </div>

        <div class = "actions">
            <button class="edit" data-id="${id}">Edit</button>
            <button class="delete" data-id="${id}">Delete</button>
        </div>
    </div>
    `
    elements.list.appendChild(tasks)
    markOfdddueDate()
    return tasks
}

/*********************************
 * Storing tasks in local storage*
 *********************************/

function Storingtasks(){
    localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks))
    createTask(tasks)
}

function getStoredtask(){
    const storedkey = localStorage.get(STORAGE_KEY);
    if(storedkey){
    tasks = JSON.parse(storedkey);
    createTask(tasks)
    }
}

getStoredtask()

你弄错了。应该是:

function getStoredtask(){
  const storedkey = localStorage.getItem(STORAGE_KEY);
  if(storedkey){
    tasks = JSON.parse(storedkey);
    createTask(tasks)
  }
}

是的,请查看初始 post 下的评论。您还必须调用函数来存储它们。你也在那里犯了错误:

应该是:

function Storingtasks(){
   localStorage.setItem(STORAGE_KEY, JSON.stringify(createTask(tasks)))
}