首页 > 解决方案 > 包含本地存储数据的表未更新

问题描述

我已经构建了一个动态 HTML 表,它从 Localstorage 获取数据。我的问题是当我更新我的班级时表格没有更新(我得到旧表格并且我在员工列表电子邮件中进行了更改,它不会在新表格中更新)我没有收到任何错误。但是当我在控制台中检查我的本地存储时,它显示的是旧的....

    constructor(name, gender, department, yy, email, skills) {
        this.name = name;
        this.gender = gender;
        this.department = department;
        this.email = email;
        this.skills = [];

    }

}

//Employee Database "Localstorage"
if(localStorage.getItem("Employee") == null) {
    var employeeList = [];
    employeeList.push (new Employee("Simon", "Male", "HR", 1999, "kk@gmail.com"));
    employeeList.push (new Employee("Mads", "Male","IT", 1999,  "1234@email.com"));
    employeeList.push (new Employee("Jessica", "Female", "Sales",1998, "Mail2@mail.dk"));
    employeeList.push (new Employee("Benjamin", "Male","IT", 1997, "blabla@mail.dk"));

    var employeeListString = JSON.stringify(employeeList);
    localStorage.setItem("Employee", employeeListString);
    document.querySelector('#employees').appendChild(buildTable(employeeList));
} else {
    var employeeList = JSON.parse(localStorage.getItem("Employee"));
}
//Function creates table for employeeLise
function buildTable(data) {
    let table = document.createElement("table");

        // Create table head and body
        table.appendChild(document.createElement("thead"));
        table.appendChild(document.createElement("tbody"));

        let fields = Object.keys(data[0]);
        let headRow = document.createElement("tr");
        fields.forEach(function (field) {
            let headCell = document.createElement("th");
            headCell.textContent = field;
            headRow.appendChild(headCell);
        });
        table.querySelector("thead").appendChild(headRow);
        data.forEach(function (object) {
            let row = document.createElement("tr");
            fields.forEach(function (field) {
                let cell = document.createElement("td");
                cell.textContent = object[field];
                if (typeof object[field] == "number") {
                    cell.style.textAlign = "left";
                }
                row.appendChild(cell);
            });
            table.querySelector("tbody").appendChild(row);
        });
        return table;

    }

document.querySelector("#employees").appendChild(buildTable(employeeList));

标签: javascripthtml

解决方案


推荐阅读