6

我有来自用户输入表单的学生列表,如下所示:

 //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 中怎么做?

4

1 回答 1

17

您想将所有学生放在这样的数组中:

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));
}
于 2013-05-23T15:24:35.587 回答