英文:
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));
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论