我正在创建一个博客,我希望将更多内容存储到本地存储中,而不是只存储一个。我该怎么做?
function saveToLocalStorage(){
var title = document.getElementById("title1");
var titlesaved=title.innerHTML;
var para = document.getElementById("p1");
var parasaved = para.innerHTML;
localStorage.setItem("Title",titlesaved);
localStorage.setItem("Paragraph",parasaved);
}
function RetrieveData(){
document.getElementById("title2").innerHTML = localStorage.getItem("Title");
document.getElementById("paragraph2").innerHTML = localStorage.getItem("Paragraph");
}
答案 0 :(得分:2)
将您的数据存储为JSON:
var data = [{Title: '', Paragraph: ''}];
localStorage.setItem("items", JSON.stringify(data));
当您需要更新/添加信息时,只需获取该JSON,解析它,编辑并放回:
var data = JSON.parse(localStorage.getItem("items"));
data.push({Title: 'a', Paragraph: ''});
localStorage.setItem("items", JSON.stringify(data));