我正在制作一个子手游戏,想从本地存储中存储和检索该人的分数及其用户名,并将其显示在排行榜div
上。我该怎么做呢?我已经看到大多数人都使用localStorage.get
和localStorage.set
,但是我不确定如何在这里实现它。
感谢您的帮助。
到目前为止,这是我的JavaScript代码:
function storeUserDetails() {
var userObject = {};
userObject.name = document.getElementById("nameinput").value;
userObject.username = document.getElementById("usernameinput").value;
userObject.password = document.getElementById("passinput").value;
userObject.repeatpassword = document.getElementById("repeatpassinput").value;
userObject.topscore = 0;
localStorage[userObject.username] = JSON.stringify(userObject);
document.getElementById("result").innerHTML = "<b>Registration
Successful<br> Please <a href = '../PHP/login.php'><font color =
'orangered'>login</font></a></b>";
}
function checkLogin() {
if (localStorage.loggedInUsername !== undefined) {
var userObj = JSON.parse(localStorage[localStorage.loggedInUsername]);
}
}
function login() {
var username = document.getElementById("usernameinput").value;
if (localStorage[username] === undefined) {
document.getElementById("result").innerHTML = "<b>Username not found. Please sign up.</b>";
return;
} else {
var userObj = JSON.parse(localStorage[username]); //Convert to object
var password = document.getElementById("passinput").value;
if (password === userObj.password) {
localStorage.loggedInUsername = userObj.username;
document.getElementById("result").innerHTML = "";
window.location = "loggedin.php";
/*sessionStorage.setItem('status', 'logged in');*/
} else {
document.getElementById("result").innerHTML = "<b>Password incorrect. Please try again.</b>"
}
}
}
function updateScore() {
rankingTable = document.getElementById("leaderboardcontainer");
tableData = document.getElementById("content");
//Username and score to be displayed here.
}
答案 0 :(得分:1)
您应该使用文档中所示的getItem,setItem和removeItem方法。
https://developer.mozilla.org/it/docs/Web/API/Window/localStorage