简体   繁体   English

需要HTML5 Localstorage帮助

[英]HTML5 Localstorage help needed

I'm fresh to JS and i was wondering how i could implement this scenario to my code. 我对JS非常了解,我想知道如何将这种情况实现到我的代码中。
Im creating a simple tapping game for android using html, css and js. 我使用html,css和js为Android创建了一个简单的点击游戏。 Whenever my object gets clicked on, 10 points gets added to score. 每当我的对象被点击时,得分将增加10分。 I need this score to saved locally. 我需要此分数保存在本地。 So when the game restarts the score is there loaded. 因此,当游戏重新启动时,就会加载分数。
Here are the game code: 这是游戏代码:

 var score = 0; $(document).ready(function() { $("#menu").hide(); $("#bug").autoBounceOff(true); $("#bug").moveTo(140); $("#bug").speed(0.8); //When bug is clicked on $("#bug").click(function() { score = score + 10; $('#score').html('Points: ' + score + '') + 10; }); }) function showMenu() { $("#menu").show(); $("#bug").css("visibility", "hidden"); $("#bug").css("animation-play-state", "paused"); return; } function resume() { $("#menu").hide(); $("#bug").css("visibility", "visible"); $("#bug").css("animation-play-state", "running"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="header"> <div id="score">Points:</div> <div id="menuheader" onclick="showMenu()">M</div> </div> <div id="menu"> <div id="start" onclick="resume()">resume</div> </div> <div id="bug"></div> <div class="bottomwall"></div> <div class="topwall"></div> <div class="leftwall"></div> <div class="rightwall"></div> 

JSFiddle JSFiddle

basic localStorage usage. 基本的localStorage使用情况。

When you starting your script, you can test if localStorage.score is already set with: 启动脚本时,可以测试localStorage.score是否已设置为:

var score = 0;
if(!localStorage.score){
    localStorage.score = 0;
}
score = parseInt(localStorage.score);

then in your click event: 然后在您的点击事件中:

localStorage.score = score + 10

please check this link can help you : 请检查此链接可以为您提供帮助:
http://www.w3schools.com/html/html5_webstorage.asp http://www.w3schools.com/html/html5_webstorage.asp
you can make an empty array and use: 您可以创建一个空数组并使用:
array_name.push() for your values. array_name.push()作为您的值。
then you can use localStorage.setItem("score" , array_name) 那么您可以使用localStorage.setItem("score" , array_name)
and you can retrieve this value again using: 您可以使用以下方法再次检索该值:
localStorage.getItem("score");
that return array values and you should check first: 返回数组值,您应该首先检查:
if it has values or not to avoid undefined or exceptions in your application. 是否具有值,以避免应用程序中未定义或异常。
if you need a demo for this just tell me now and i will upload it. 如果您需要演示,请立即告诉我,我将上传它。

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

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