简体   繁体   中英

Print Local Storage onto page

How can I show the users high score in my game? I can't use onload() , so how can I show the stored high scores? Here is my code to get scores.

var hs = localStorage["hs"];

function myFunction() {
    $("#demo").text(hs);
}
<script type="text/javascript">
    localStorage.setItem("highscore","100");
    var v=localStorage.getItem("highscore");
    alert(v);
</script>

you need to use setItem() for assigning value to the variable and getItem() for fetching the value

This will help you.

<!DOCTYPE html>
<html>
    <head>
        <title>A game</title>
    </head>
    <body>
        <div id="showscore"></div>
        // Keep the script tag at the end of your HTML code.
        <script type="text/javascript">
            //localStorage.setItem("highScore","564544");
            var highScore = localStorage.getItem("highScore"); 
            // Considering you already have highScore set in local storage.
            // Uncomment your line number 10 if you want to set in local storage
            if(highScore){
                document.getElementById('showscore').innerHTML = highScore;
            }
            else{
                document.getElementById('showscore').innerHTML = "Play your first game";            
            }
        </script>
    </body>
</html>

You can use innerHTML dom attribute here to insert your highscore stored in local storage.

Make sure you insert the script at the end of html code, as the script needs the all elements to be rendered first.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM