我只能将一个学生的详细信息存储到本地存储中。如何在localstorage中使用相同的表单存储多个学生详细信息?

时间:2018-03-24 17:10:42

标签: javascript jquery local-storage

$("#smtbtn").click(function(){

    var username = $("#username").val()
    var email = $("#email").val()    
    var phone = $("#phone").val()
    var textcalendar = $("#text-calendar").val()
    var age = $("#age").val()
    var pic = $("#pic").val()
    var address = $("#address").val()
    var m1 = $("#m1").val()
    var m2 = $("#m2").val()
    var skill = $("#skill").val()

var student= [username,email,phone,textcalendar,age,pic,address,m1,m2,skill];
localStorage.setItem("studentdetails", JSON.stringify(student));

var retrievedData = localStorage.getItem("studentdetails");
var movies1 = JSON.parse(retrievedData);

console.log(movies1);
})

2 个答案:

答案 0 :(得分:0)

您可以简单地添加另一个级别,如下所示:

var students = localStorage.getItem("students");

if (students) {
    students = JSON.parse(students);
} else {
    students = {};
}

students[username] = [username,email,phone,textcalendar,age,pic,address,m1,m2,skill];

localStorage.setItem("students", JSON.stringify(students));

然后如果你调用getItem,你将拥有一个键值对的对象,其中键是username,值是student对象。

修改

测试功能:

    var students = localStorage.getItem("students");

    if (students) {
        students = JSON.parse(students);
    } else {
        students = {};
    }

   console.log(students);

    students["ha"] = ["ha", "haha"];

    localStorage.setItem("students", JSON.stringify(students));

答案 1 :(得分:0)

设置为localstorage:

students[username] = 
[username,email,phone,textcalendar,age,pic,address,m1,m2,skill];

localStorage.setItem("students", JSON.stringify(students));

从localstorage获取:

var students = localStorage.getItem("students");

if (students) {
    students = JSON.parse(students);
} else {
    students = {};
}