我想在本地存储中设置新对象。

huangapple go评论58阅读模式
英文:

I want to set new object in local storage

问题

function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');

    let notesObj = []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote', JSON.stringify(notesObj));
}
英文:
function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');
    
    let notesObj = []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote',JSON.stringify(notesObj));
}

This code is everyTime changing the older value I want to get a new object in local storage

答案1

得分: 2

可能你想要将注释添加到现有的 localStorage 数据中,所以在这里你可以检查是否已经设置了 userNote,如果已经设置了,就获取它,否则设置为空数组,

let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

你的整个函数应该像这样,

function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');
    
    let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote', JSON.stringify(notesObj));
}
英文:

Probably you want to add note into your existing localStorage data so here you can check if there is userNote is already set before then take it or set an empty array,

let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

Your whole function would be like this,

function addNote() {
    const givenTitle = document.getElementById('titleInput');
    const givenNote = document.getElementById('noteInput');
    
    let notesObj = JSON.parse(localStorage.getItem("userNote")) || []

    let myObj = {
        title: givenTitle.value,
        note: givenNote.value,
    }

    notesObj.push(myObj)

    localStorage.setItem('userNote',JSON.stringify(notesObj));
}

huangapple
  • 本文由 发表于 2023年6月1日 23:14:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76383388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定