我希望表格中的数据按升序排列,因此得分最高的人应位于表格的顶部,而得分最低的人员应位于表格底部。我创建了一个数组,并使用for循环来对数据进行排序,但表中没有任何内容。我创建了一个JSFiddle Here
/* Rank Table */
function displayTable() {
var data = [];
data = {firstName: data.FirstName, lastName: data.LastName, topScore: data.Score};
var getData = function(key){return JSON.parse(localStorage[key]);}
var highScoreTable = "<tr><th>First Name</th><th>Last Name</th><th>Score</th></tr>\n";
for (var key in localStorage) {
if (key !== 'loggedInUser') {
data = getData(key);
for (var i = 0; i < data.length; i++) {
highScoreTable += "<tr><td>" + data[i].firstName + "</td><td>" + data[i].lastName + "</td><td>" + data[i].topScore + "</td></tr>";
}
}
}
document.getElementById('rankTable').innerHTML = highScoreTable;
}
答案 0 :(得分:1)
您的实施几乎没有问题,请参阅下面的代码更改:
/* Register */
function storeUserDetail() {
const fNameInput = document.getElementById("firstNameInput").value;
const lNameInput = document.getElementById("lastNameInput").value;
const uNameInput = document.getElementById("userNameInput").value;
const pWordInput = document.getElementById("passWordInput").value;
const yourScoreInput = document.getElementById("scoreInput").value;
const storeDetails = {
firstName: fNameInput,
lastName: lNameInput,
username: uNameInput,
password: pWordInput,
score: yourScoreInput
};
const username = storeDetails.username;
// save details to localStorage using username as key
localStorage[username] = JSON.stringify(storeDetails);
}
/* Log In */
function loginUser() {
const username = document.getElementById("uNameInput").value;
const password = document.getElementById("pWordInput").value;
const storeDetails = JSON.parse(localStorage[username]);
storeDetails.username = document.getElementById("uNameInput").value;
storeDetails.password = document.getElementById("pWordInput").value;
localStorage.loggedInUser = username;
}
const data = [];
const getData = key => {
return JSON.parse(localStorage[key]);
};
/* Rank Table */
function displayTable() {
let tableBody = '';
const tableHeader =
"<tr><th>First Name</th><th>Last Name</th><th>Score</th></tr>\n";
for (let key in localStorage) {
if (key !== "loggedInUser") {
data.push(getData(key));
}
}
for (let user of data) {
if (tableBody) {
tableBody +=
`<tr><td>
${user.firstName}
</td><td>
${user.lastName}
</td><td>
${user.score}
</td></tr>`;
} else {
tableBody =
`<tr><td>
${user.firstName}
</td><td>
${user.lastName}
</td><td>
${user.score}
</td></tr>`;
}
}
document.getElementById("rankTable").innerHTML = "";
document.getElementById("rankTable").innerHTML = tableHeader + tableBody;
}
您可以查看完整来源here。