简体   繁体   English

在页面上打印本地存储

[英]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? 我不能使用onload() ,那么如何显示存储的高分? 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 您需要使用setItem()将值分配给变量,并使用getItem()来获取值

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. 您可以在此处使用innerHTML dom属性插入存储在本地存储中的高分。

Make sure you insert the script at the end of html code, as the script needs the all elements to be rendered first. 确保将脚本插入html代码的末尾,因为脚本需要首先呈现所有元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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