如何使用本地存储设置缓存

时间:2018-08-14 12:23:20

标签: javascript caching local-storage session-cookies

我有一个广告框,我想通过单击x按钮将其关闭,所以在它关闭后,我不想一直等到拥有缓存的24小时后才创建了本地存储,但是它无法正常工作,我应该怎么做我编辑我的示例

    var showCase = Math.round(+new Date() / 1000);

        document.getElementById("close_ads").addEventListener("click", function () {
        if (typeof localStorage.showCase == 'undefined' || parseInt(localStorage.showCase) <= (showCase - 3600)) {            
          localStorage.showCase = showCase;
          document.getElementById('reklam_box').style.display = 'none';
        }
        });
      
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>

3 个答案:

答案 0 :(得分:2)

您需要使用Localstorage .setItem().getItem进行检查。

https://www.taniarascia.com/how-to-use-local-storage-with-javascript/

所以这样

// set the item
localStorage.setItem('showCase', 3600);

//get the item
var showCase = localStorage.getItem('showCase');

答案 1 :(得分:1)

有用的链接:

https://johnresig.com/blog/dom-storage/

https://developer.mozilla.org/en-US/docs/Web/API/Storage

注意:使用带对象数组的localStorage时,必须像这样保存它:

只需将对象转换为JSON字符串:

localStorage.setItem("savedData", JSON.stringify(objects));

var objects = JSON.parse(localStorage.getItem("savedData")));

答案 2 :(得分:1)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example</title>
</head>
<body>
    <div id="ads_box">
        Hi..I am a ads..
        <span id="close_ads">Close ads and don't show unit for 24 hours</span>
    </div>
    <script>
        var dontShowUntil = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);

        document.getElementById("close_ads").addEventListener("click", function () {
            localStorage.dontShowUntil = dontShowUntil;
            document.getElementById('ads_box').style.display = 'none';
        });

        if (new Date(localStorage.dontShowUntil) > new Date()) {
            document.getElementById('ads_box').style.display = 'none';
        }
    </script>
</body>
</html>