我有以下表格的学生名单来自用户输入表格:
//student form input for 1st time
var student={name:"a",roll:"9",age:13}
//student form input for 2nd time
var student={name:"b",roll:"10",age:14}
//student form input for 3rd time
var student={name:"c",roll:"11",age:15}
实际上,我正在开发phonegap应用程序。每次用户提交表单输入即学生信息时,我想将它们保存到本地存储中。最后,在线时,我想同步它们。我知道我可以将它们存储在本地存储中,如下所示:
localStorage.setItem("studentinfo", JSON.Stringfy(student));
但是,当我保存第二个学生信息时,这将删除本地存储中的第一个学生信息。
事实上,当我分别保存第一,第二和第三个输入时,我想将它们添加到localstorage数组中,最后localstorage中的结果应该像
key=studentlist,
value=[
{name:"a",roll:"9",age:13},
{name:"b",roll:"10",age:14},
{name:"c",roll:"11",age:15}
]
如何在localstorage或phonegap localstorage中完成?
答案 0 :(得分:11)
您希望将所有学生都安排在这样的数组中:
var students = [];
students.push({name:"a",roll:"9",age:13});
students.push({name:"b",roll:"10",age:14});
students.push({name:"c",roll:"11",age:15});
然后将其存储在localStorage
:
localStorage.setItem('studentsInfo', JSON.stringify(students));
最好的方法是使用这样的函数:
// When you get more student information, you should:
var addNewStudent = function (name, roll, age) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var students = JSON.parse(localStorage.getItem('studentsInfo') || [];
// add to it,
students.push({name: name, roll: roll, age: age});
// then put it back.
localStorage.setItem('studentsInfo', JSON.stringify(students));
}