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

Session Storage: how to store multiple objects

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

顺便说一句...必须是纯 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));

}

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

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

正在工作...

    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));


}