Currently, my code shows the score of the user that's logged in. I want to show the highest score obtained by each user on the leaderboard until the top 10.
js from index.html
<script>
loadRankingTable();
window.onload = () => {
//Check login
if (sessionStorage.loggedInUser !== undefined) {
let oldData = localStorage.getItem(sessionStorage.loggedInUser);
console.log(JSON.parse(oldData))
if (oldData) {
oldData = JSON.parse(oldData);
oldData.topScore = highscore;
localStorage.setItem(sessionStorage.loggedInUser, JSON.stringify(oldData));
}
document.getElementById("Greeting").innerHTML = sessionStorage.loggedInUser;
}
}
</script>
prac.js
function loadRankingTable(){
let str = "<table><tr><th>Rank</th><th>Name</th><th>Score</th></tr>";
for(let key of Object.keys(localStorage)){
let usr = JSON.parse(localStorage[key]);
str += "<tr><td>" + "1" + "</td><td>" + sessionStorage.loggedInUser + "</td><td>" + highscore + "</td></tr>";
}
str += "</table>";
document.getElementById("Ranking").innerHTML = str;
}
The highscore gets stored in the local storage, but I want the logged in user's highscore shown next to their name on the leaderboard, up till the top 10.
Try this: (others have permission to copy and edit this)
function load(){ var userscores = { "ex1": 10, "noncy": 40, "del3tus": 24, "the_r0ck": 8, "MONSTER_OSITY": 120 }; var max = 0; var sorted = []; for(var prop in userscores){ if(userscores[prop] >= max){ max = userscores[prop]; } } var cur = max; for(var i = max; i > 0; i--){ for(var prop in userscores){ if(userscores[prop] == i){ sorted.push(prop); } } } var html = ""; for(var i = 0; i < sorted.length; i++){ html = "<tr><td>" + (i + 1) + "</td><td>" + sorted[i] + "</td><td>" + userscores[sorted[i]] + "</td></tr>"; document.getElementById("leaderboard").innerHTML += html; } }
<button onclick="load();">Load leaderboard</button> <table id="leaderboard" border="1" cellSpacing="0px"><tr><th>#</th><th>Name</th><th>Points</th></tr></table>
If that doesn't work, let me know. You can also change it to make it fit better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.