如何保存Javascript变量?

时间:2016-05-01 12:23:28

标签: javascript variables

我正在开展一个涉及全球“银行”积分的项目。

我一直在尝试使用此代码的snippits,但我无法在刷新后保存变量。

    <!DOCTYPE HTML>
<html>
<head>
    <title>Javascript variable testing</title>
</head>

<body>
    <script type="text/javascript">
    var clicks = 500000;

    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;

    };

    </script>
    <button type="button" onClick="onClick()">Click this bit</button>
    <p>Clicks: <a id="clicks">500000</a></p>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

将数据设置为localStorage。这是文档https://developer.mozilla.org/en/docs/Web/API/Window/localStorage

这可以在页面刷新后获得值。

使用以下设置值: localStorage.setItem('key', 'value');

刷新页面后从本地存储中获取价值 localStorage.getItem('key');

否则您可以使用sessionStorageWeb SQL&amp; cookies

示例:

var clicks = 500000;

localStorage.setItem('clicks', clicks); // set you value to localStorage

function onClick() {
  clicks += 1;
  localStorage.setItem('clicks', clicks); // update you value
  document.getElementById("clicks").innerHTML = clicks;

}

window.onload = function() {
  clicks = localStorage.getItem('clicks'); // get your value from localStorage
};
<!DOCTYPE HTML>
<html>

<head>
  <title>Javascript variable testing</title>
</head>

<body>
  <button type="button" onclick="onClick()">Click this bit</button>
  <p>Clicks: <a id="clicks">500000</a>
  </p>

</body>

</html>