简体   繁体   中英

Saving number data to a local storage

I'm starting with something simple like an incremental browser game, you basically just click a button and the number counter goes up, and that number becomes currency you can use to buy upgrades that make it so that the number counter goes up by itself.

The only thing I've been trying to figure out is how to make a save function/have all the data saved to a localStorage, so that when the page is refreshed or browser is closed, the numbers don't reset to 0.

Here's part of the javascript code that I'm trying to store:

var cookies = 0;

function cookieClick(number){
    cookies = cookies + number;
    document.getElementById("cookies").innerHTML = cookies;
};

var cursor = 0;

function buyCursor(){                                            
    var cursorCost = Math.floor(10 * Math.pow(1.1,cursor));     
    if(cookies >= cursorCost){                                   
        cursor = cursor + 1;                                   
        cookies = cookies - cursorCost;                         
        document.getElementById('cursor').innerHTML = cursor;  
        document.getElementById('cookies').innerHTML = cookies;  
    };
    var nextCost = Math.floor(10 * Math.pow(1.1,cursor));       

    document.getElementById('cursorCost').innerHTML = nextCost;  
};

window.setInterval(function(){

    cookieClick(cursor);

    }, 1000);

Here's the HTML code:

  <body bgcolor="#2E2E2E"> <div style="text-align: center"> <button onclick="cookieClick(1)"><font size=4>Click</font></button> <br /> <font size="5" color="red">Cash: </font> <span id="cookies">0</span> <div> <br /> <DIV style="position: absolute; top:370px; left:230px; width:300px; height:20px"> <button onclick="buyCursor()">Buy Cursor</button> <br /> Cursors: <span id="cursor">0</span> <br /> Cursor Cost: <span id="cursorCost">10</span> <script type="text/javascript" src="main.js"></script> </body> </html> 

This is what I tried using to store the data to localStorage (but it obviously didn't work):

<script>
// Check browser support
if (typeof(Storage) != "undefined")
  // Store
  localStorage.cookies;
  // Retrieve
  {
  document.getElementById("cookies").innerHTML=localStorage.cookies;
  }
else
  {
  document.getElementById("cookies").innerHTML="Sorry, your browser does not support Web Storage...";
  }
</script>

So my question is, how do I get this thing to work with the code I'm using?

you might want to consider using something like html5s local storage. W3 Schools example

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