在本地存储中设置对象的值

时间:2020-06-29 04:50:47

标签: javascript json storage local

需要在本地存储中添加对象并同时使用它们。但是代码显示“ 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))
})

0 个答案:

没有答案