问题
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