尝试将数据存储在Clicker网站中 [英] Trying to store data in a clicker website

查看:86
本文介绍了尝试将数据存储在Clicker网站中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试存储一个名为score的变量,无论您何时刷新,都将反复使用它.我不知道是什么代码.我尝试了一些方法,但似乎都没有用.

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.

这是我的答题器网站.但是,当我尝试使用JavaScript进行存储时,它不能与window.onloadonload=一起使用.另外,我的负载可能是正确的,因为我有一个score = data和一个document.getElementById('points').innerHTML = score;.

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;.

我的代码如下所示:

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();
};

推荐答案

SaveData()中更改此行:

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

对此:

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

LoadData()中的这一行:

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

对此:

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

此外,无需每次单击都更新事件.您可以将该代码移出Click()函数:

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++;
}

然后将您从setInterval()获取的ID值(而不是函数引用)传递给clearInterval().像这样:

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);

这篇关于尝试将数据存储在Clicker网站中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆