如何通过删除按钮清除localStorage内JSON数组中的特定JSON对象?

时间:2018-10-12 23:50:27

标签: javascript jquery html local-storage

我有一个程序,可以简单地将学生添加到表中,并将该信息存储到本地存储中。我可以添加学生并查看存储在本地存储中的数据,但是我的最大问题是想出如何在添加对象后单击按钮(而不清除所有本地存储)来删除本地存储中的特定对象。

测试链接:https://www.chriscaldwelldev.com/studentIA/student.html

以下是表和输入(HTML):

<body>

    <div class="container">

        <h1 class="title">Student Manager</h1>

        <div class="controlCenter">
            <table id="studentTable" class="table">
                <thead>
                    <tr>
                        <th>Student Number:</th>
                        <th>Name:</th>
                        <th>Address:</th>
                        <th>Phone Number:</th>
                        <th>GPA:</th>
                        <th>Academic Plan:</th>
                        <th>Level:</th>
                        <th>Status:</th>
                    </tr>
                </thead>
                <tbody id="students"></tbody>
                <tbody>
                    <tr>
                        <td><input type="text" id="studentN"></td>
                        <td><input type="text" id="name"></td>
                        <td><input type="text" id="address"></td>
                        <td><input type="text" id="phoneN"></td>
                        <td><input type="text" id="gpa"></td>
                        <td><input type="text" id="ap"></td>
                        <td><select id="selectL" name="SelectL">
                            <option value="" disabled selected>Select...</option>
                            <option value="freshman">Freshman</option>
                            <option value="sophomore">Sophomore</option>
                            <option value="junior">Junior</option>
                            <option value="senior">Senior</option>
                            <option value="graduate">Graduate</option>
                        </select></td>
                        <td><select id="selectS" name="SelectS">
                            <option value="" disabled selected>Select...</option>
                            <option value="active">Active</option>
                            <option value="inactive">Inactive</option>
                        </select></td>
                    </tr>
                </tbody>
            </table>

            <input id="add" class="addButton" value="ADD">

        </div>

    </div>

</body>

这是JS:

// when the document loads
            $(function(){

                // add an onclick function to the id=add button 
                $("#add").click(function(){

                    var studentN = $("#studentN").val();
                    var name = $("#name").val();
                    var address = $("#address").val();
                    var phoneN = $("#phoneN").val();
                    var gpa = $("#gpa").val();
                    var ap = $("#ap").val();
                    var selectL = $("#selectL").val();
                    var selectS = $("#selectS").val();

                    if(studentN==null || name==null || address==null || phoneN==null || 
                        gpa==null || ap==null || selectL==null || selectS==null){
                        alert("All Fields Are Required to Add a Student");
                        return;
                    }

                    //create JSON object with text inputs with key:value pairs
                    var student = {
                        studentN: studentN,
                        name: name,
                        address: address,
                        phoneN: phoneN,
                        gpa: gpa,
                        ap: ap,
                        selectL: selectL,
                        selectS: selectS
                    }

                    //load local storage
                    var students = JSON.parse(localStorage.getItem("students"));

                    //if empty
                    if(!students){
                        students = [];   
                    }

                    students.push(student);

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

                    // store a copy of the row in the body
                    var row = $("<tr>");

                    // store a copy of the current state in the <td> tag  
                    var studentNData = $("<td>");
                    // now change the innerHTML for that <td> 
                    studentNData.html(studentN);
                    // append the new value to our row
                    row.append(studentNData);

                    (...)

                    // store a copy of the current state for the next <td> tag
                    var selectSData = $("<td>");
                    // change the inner html of the <td>
                    selectSData.html(selectS);
                    // append the new value to our row
                    row.append(selectSData);

                    var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
                    row.append(deleteButton);

                    // on the DOM, put the new row on the top of the list
                    $("#students").prepend(row);

                    // reset the values of the text inputs to empty strings 
                    $("#studentN").val("");
                    $("#name").val("");
                    $("#address").val("");
                    $("#phoneN").val("");
                    $("#gpa").val("");
                    $("#ap").val("");
                    $("#selectL").val("");
                    $("#selectS").val("");


                });

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

                $("#studentTable").on('click', '.deleteButton', function () {
                    $(this).closest('tr').remove();
                    //I can't think of what to do here...

                });

                if (students) {

                    // loop through the entire JSON array stored in local storage
                    for (i in students) {

                        // get a current copy of the content in the row
                        var row = $("<tr>");

                        // store a copy of the current state in the <td> tag, update the innerHTML, then append it to the DOM at the end of the row
                        var studentNData = $("<td>");
                        studentNData.html(students[i].studentN);
                        row.append(studentNData);

                        (...)

                        var selectSData = $("<td>");
                        selectSData.html(students[i].selectS);
                        row.append(selectSData);

                        var deleteButton = $("<td>" + "<input type=\"button\" class=\"deleteButton\" value=\"X\">");
                        row.append(deleteButton);

                        // now add the row to the DOM at the beginning of the list
                        $("#students").prepend(row);
                    }

                }

});

我认为我需要做的主要工作都是在deleteButton onclick中完成。我已经考虑了一些想法,但是它们似乎超级错误。如果可以的话,我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

您可以使用的一种解决方案是在删除按钮上添加一个data-studentn属性。然后,当单击删除按钮时,您可以从localStorage加载students数组,删除具有该studentn的学生,然后保存新的students数组。

更改

"<input type=\"button\" class=\"deleteButton\" value=\"X\">"

"<input type=\"button\" class=\"deleteButton\" value=\"X\" data-studentn=\"" + students[i].studentN + "\" >"

注意:请记住在创建删除按钮的其他位置执行类似的操作。

//I can't think of what to do here...下,您可以执行以下操作:

var deletedStudentN = $(this).attr('data-studentn');
var students = JSON.parse(localStorage.getItem("students"));
students = students.filter(function(student) {
    return student.studentN != deletedStudentN;
});
localStorage.setItem("students", JSON.stringify(students));