在排名表中存储更多用户

时间:2017-12-08 21:36:24

标签: javascript

我想在排名表上存储更多用户,并在表格中显示他们的名字和姓氏。但每次新用户注册时,它都会替换表中的第一个用户。我该如何解决?我创建了一个JSFiddle Here

/* Register */
function storeUserDetail() {
    var fNameInput = document.getElementById("firstNameInput").value;
    var lNameInput = document.getElementById("lastNameInput").value;
    var uNameInput = document.getElementById("userNameInput").value;
    var pWordInput = document.getElementById("passWordInput").value;
    var storeDetails = {};
    storeDetails.FirstName = fNameInput
    storeDetails.LastName = lNameInput
    storeDetails.Username = uNameInput
    storeDetails.Password = pWordInput
    localStorage[storeDetails.Username] = JSON.stringify(storeDetails);                  
}

/* Log In */
function loginUser() {
    var Username = document.getElementById("uNameInput").value;
    var Password = document.getElementById("pWordInput").value;
    var storeDetails = JSON.parse(localStorage[Username]);
    storeDetails.Username = document.getElementById("uNameInput").value;
    storeDetails.Password = document.getElementById("pWordInput").value;
    localStorage.loggedInUser = Username;
}

/* Rankings Table */
function displayTable() {
    var getData = JSON.parse(localStorage[localStorage.loggedInUser]); 
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th></tr>\n";
    for(var key in localStorage) {
        if(key !== localStorage.loggedInUser) {
            highScoreTable += "<tr><td>" + getData.FirstName + "</td><td>" + getData.LastName + "</td></tr>";
        }
    } 
    document.getElementById('rankTable').innerHTML = highScoreTable;
}

1 个答案:

答案 0 :(得分:1)

我认为getData应该是一个功能。当dispalyTable

时,它适用于我
/* Rankings Table */
function displayTable() {
    var getData = function(key) { return JSON.parse(localStorage[key]); }
    var highScoreTable = "<tr><th>First Name</th><th>Last Name</th></tr>\n";
    for (var key in localStorage) {
        if (key !== 'loggedInUser') {
            var data = getData(key);
            highScoreTable += "<tr><td>" + data.FirstName + "</td><td>" + data.LastName + "</td></tr>";
        }
    }
    document.getElementById('rankTable').innerHTML = highScoreTable;
}

我更新了getData,并针对本地存储密钥key检查'loggedInUser'而不是值。或者它可以是if(localStorage[key] !== localStorage.loggedInUser)

https://jsfiddle.net/wapapzyd/