How do I set local storage on a bootstrap modal?

大憨熊 提交于 2021-01-27 12:36:32

问题


The "modal-2" id opens a modal for a survey.

All I want is for this particular modal, to re-appear once every 24 hours after someone clicks the close button.

$(document).ready(function(){
    var modals = ['#events'];
    if (window.location.hash && ~modals.indexOf(window.location.hash)) {
        $(window.location.hash).modal();
    }
    $("#modal-2").modal('show');
    $(".modal:not(.noclose)").on("click","a",function(){
        $(this).closest(".modal").modal("hide");
    });
});

回答1:


You can set current timestamp Date.now() to the localStorage and check it every time you need to decide whether to show the modal or not. Example code:

var twentyFourHoursInMs = 24 * 60 * 60 * 1000;
var lastTimestamp = Number(localStorage.getItem("last-showed-at"));
var currentTimestamp = Date.now();
if ((currentTimestamp - lastTimestamp) >= twentyFourHoursInMs) {
    localStorage.setItem("last-showed-at", currentTimestamp);
    $("#your-modal-id").modal("show");
    // Display modal once again
}

So this is the full code in your case:

$(document).ready(function(){
    var modals = ['#events'];
    if (window.location.hash && ~modals.indexOf(window.location.hash)) {
        $(window.location.hash).modal();
    }

    $(".modal:not(.noclose)").on("click","a",function(){
        $(this).closest(".modal").modal("hide");
    });

    var currentTimestamp = Date.now();

    $("#cul8a").on("hidden.bs.modal", function () {
        localStorage.setItem("last-showed-at", currentTimestamp);
    });

    // Check for modal eligibility

    var twentyFourHoursInMs = 24 * 60 * 60 * 1000;
    var lastTimestamp = Number(localStorage.getItem("last-showed-at"));

    if ((currentTimestamp - lastTimestamp) >= twentyFourHoursInMs) {
        setTimeout(function() {
            localStorage.setItem("last-showed-at", currentTimestamp);
            $("#cul8a").modal("show");
        }, 4000);
    }
});


来源:https://stackoverflow.com/questions/36749533/how-do-i-set-local-storage-on-a-bootstrap-modal

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