Trying to store data in a clicker website

你。 提交于 2020-02-04 02:33:40

问题


I am trying to store a variable called score that you use again and again no matter when you refresh. What I cannot figure out is what would be the code for that. I tried some ways but none of them seem to work at all.

This is for my clicker website. But when I try using JavaScript to store it, it does not work with window.onload and as well as onload=. Also my load maybe is right because I have a score = data with a document.getElementById('points').innerHTML = score;.

My code is shown below:

var score = 0;

setInterval(SaveData, 10);

setInterval(Click, 1000); // Every full second allow clicking ONE point.

function Click() {
  score++;
  document.getElementById('btn').onclick = function() {
    document.getElementById('demo').innerHTML = score;
    clearInterval(Click);
  }
}

function SaveData() {
  // What saves the variable score
  localStorage['save'] = btoa(JSON.stringify(score));
}

function LoadData() {
  score = JSON.parse(atob(localStorage['save']))
  document.getElementById('demo').innerHTML = score;
}

window.onload = function() {
  // When the window loads do this
  LoadData();
};

回答1:


Change this line in SaveData():

localStorage['save'] = btoa(JSON.stringify(score));

to this:

localStorage.setItem('save', btoa(JSON.stringify(score)));

and this line in LoadData():

score = JSON.parse(atob(localStorage['save']))

to this:

score = JSON.parse(atob(localStorage.getItem('save')));

Also, there is no need to update the event with every click. You can move that code out of the Click() function:

document.getElementById('btn').onclick = function() {
  document.getElementById('demo').innerHTML = score;
  clearInterval(Click);
}

function Click() {
  score++;
}

And you pass to clearInterval() the ID value that you get back from setInterval(), not a function reference. Something like:

var timer = setInterval(Click, 1000);
clearInterval(timer);


来源:https://stackoverflow.com/questions/58175822/trying-to-store-data-in-a-clicker-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!