首页 > 解决方案 > 在本地存储中设置对象的值

问题描述

需要在本地存储中添加对象并同时使用它们。但显示“noteObj.push 不是函数”的代码

// add a Event Listener in #add-btn and gat 2 input textlet addBtn = document.getElementById("add-btn");
addBtn.addEventListener("click", function (e) {
    let addTextHeading = document.getElementById('add-text-heading').value;
    let addTextBody = document.getElementById('add-text-body').value;
    // get value form localStorage
    let notes = localStorage.getItem('notes');
    if (notes == null) {
        noteObj = []
    }
    else {
        noteObj = JSON.parse(notes)
    }
    // add value in localStorage
    let myObj = {
        heading: addTextHeading,
        body: addTextBody
    }
    noteObj.push(myObj)
    localStorage.setItem("notes", JSON.stringify(noteObj))
})

标签: javascriptjsonstoragelocal

解决方案


推荐阅读