会话存储:如何存储多个对象

时间:2015-02-19 12:47:51

标签: javascript javascript-objects session-storage

我试图将多个学生对象(从表单提交构建)存储到会话存储中,然后最终循环会话存储并在页面上显示它们。我不是很熟悉这个和它的第一个裂缝...... 我如何存储多个学生?我觉得我需要一个追加......我每次只是覆盖...... 谢谢!

btw ...必须是纯粹的JS

HTML

             <div id="infoStyle" class="col-lg-6 center-block infoWindow animated">
                <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
                <h4>First Name : <input id="fName" type="text" pattern="[A-Za-z]{50}" title="50 characters or less"></h4>
                <h4>Last Name : <input id="lName" type="text" pattern="[A-Za-z]{50}" title="50 characters or less"></h4>
                <h4>Email Address : <input id="email" type="email"></h4>
                <br>
                <a onclick="createStudent()" class="btn btn-info" role="button">Create Student</a>
                <br><br>
                <a onclick="cancel()" class="btn btn-danger" role="button">Cancel</a>
             </div>

JS

    function createStudent(){

    var student = new Object();

    student.fName = document.getElementById('fName').value;
    student.lName = document.getElementById('lName').value;
    student.email = document.getElementById('email').value;

    sessionStorage.setItem('student', JSON.stringify(student));

    var retrievedObject = sessionStorage.getItem('student');
    console.log('retrievedObject: ', JSON.parse(retrievedObject));

}

2 个答案:

答案 0 :(得分:2)

1)您需要存储到array,但在此之前,您需要在strongStorage上检查数组学生是否已经存在

2)然后将新学生添加到数组中,并将其存储到localstorage

3)当您检索数据时,没有任何变化,它会纠正您所写的内容

function createStudent(){


      // this is how you set it
    var newStudent = new Object();

    newStudent .fName = document.getElementById('fName').value;
    newStudent .lName = document.getElementById('lName').value;
    newStudent .email = document.getElementById('email').value;

    if(sessionStorage.student)
    {
     student= JSON.parse(sessionStorage.getItem('student'));
    }else{
     student=[];
    }
    student.push(newStudent )
    sessionStorage.setItem('student', JSON.stringify(student));

       // this is how you will retrive it

    var retrievedObject = sessionStorage.getItem('student');
    console.log('retrievedObject: ', JSON.parse(retrievedObject));

}

以下是jsfiddle

答案 1 :(得分:0)

...工作

    function createStudent(){

    var newStudent = new Object();

    newStudent.fName = document.getElementById('fName').value;
    newStudent.lName = document.getElementById('lName').value;
    newStudent.email = document.getElementById('email').value;

    if(sessionStorage.student)
    {
     student= JSON.parse(sessionStorage.getItem('student'));
    }else{
     student=[];
    }
 student.push(newStudent )   
    console.log(student);
    sessionStorage.setItem('student', JSON.stringify(student));

    var retrievedObject = sessionStorage.getItem('student');
    console.log('retrievedObject: ', JSON.parse(retrievedObject));


}