我将表格中的数据存储在localstorage中,格式如下:
Object {title: "dsadasds", dueDate: "dsadasdsa", summary: "dsadadas", body: "dasdasdas"}
Object {title: "dasdadsa", dueDate: "dasdasdadasda", summary: "dsadasdasd", body: "dasdasdas"}
每次用户提交表单时,此数据都存储在localstorage中。现在在另一个页面'localhost:3000 / notes'我想显示存储在localStorage中的所有这些对象。目前使用以下代码,它只显示最后提交的对象。
var form = $('#form'),
formTitle = $('#title'),
formDueDate = $('#dueDate'),
formSummary = $('#summary'),
formBody = $('#body');
var title = formTitle.val();
var dueDate = formDueDate.val();
var summary = formSummary.val();
var body = formBody.val();
var newContent2 = $('#new-content2')
var test = {};
test = {
title: title,
dueDate: dueDate,
summary: summary,
body: body
}
localStorage.setItem('test', JSON.stringify(test));
var LocalStoredData = JSON.parse(localStorage.getItem('test'));
console.log(LocalStoredData);
//for retrieving data from locastorage
var retrievedData = localStorage.getItem('test');
var text = JSON.parse(retrievedData);
var showTitle = text["title"];
var showDueDate= text["dueDate"];
var showSummary = text["summary"];
var showBody = text["body"];
$('#showTitle').html(showTitle);
$('#showDueDate').html(showDueDate);
$('#showSummary').html(showSummary);
$('#showBody').html(showBody);
我需要循环遍历所有对象(或任何其他机制)以从localStorage中提取所有对象,并在网页上的适当div中显示它们。我尝试将检索代码放在循环中:
for(var i=0;i<localStorage.length;i++)
但是使用这个循环它没有显示任何东西。如何显示localStorage中存在的所有对象。
答案 0 :(得分:1)
您正在寻找
for (var i=0; i<localStorage.length; i++) {
var key = localStorage.key(i);
var item = localStorage.getItem(key);
try {
item = JSON.parse(item);
} catch(e) {
console.log(key+" is not in JSON format");
}
…
}
答案 1 :(得分:0)
您还可以使用Object.keys
轻松获取LocalStorage的所有内容:
Object.keys(localStorage).forEach(key => {
console.log(key, localStorage.getItem(key))
})