簡體   English   中英

如何使用本地存儲設置緩存

[英]How to set a cache with Local Storage

我有一個廣告框,我想通過單擊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> 

您需要使用Localstorages .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');

有用的鏈接:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM