我需要在本地存储中存储和更新时间戳,以便在一分钟后每次都会执行modal。我希望仅当时间戳已过期或超过一分钟时,模式才会出现在刷新时。一分钟的持续时间仅用于测试目的。目标是每天只向用户显示一次模式。这是我到目前为止的情况。它仅在刷新时显示模式,并存储本地存储密钥。但一分钟后,刷新时不会显示模式,应该显示。感谢您的帮助。
$(document).ready(function() {
function shouldShowModal() {
const lastTimestamp = localStorage.getItem("modalTimestamp");
if (!lastTimestamp) {
return true;
}
const parsedTimestamp = parseInt(lastTimestamp, 10);
let expiryLimit = new Date(parsedTimestamp);
expiryLimit = expiryLimit.setMinutes(expiryLimit.getMinutes() + 1);
return new Date() > expiryLimit;
}
if (window.localStorage) {
const currentUser = '<%= current_user %>';
const currentTime = new Date($.now());
if (currentUser && shouldShowModal()) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
localStorage.setItem('modalTimestamp', currentTime);
}
}
}
更新了使用@Barmar解决方案:
$(document).ready(function() {
function shouldShowModal() {
const lastTimestamp = localStorage.getItem("modalTimestamp");
if (!lastTimestamp) {
return true;
}
const parsedTimestamp = parseInt(lastTimestamp, 10);
let expiryLimit = new Date(parsedTimestamp);
expiryLimit = expiryLimit.setHours(expiryLimit.getHours() + 24);
return new Date() > expiryLimit;
}
if (window.localStorage) {
const currentUser = '<%= current_user %>';
const currentTime = new Date();
if (currentUser && shouldShowModal()) {
swal ({
icon: 'warning',
text: 'Notice text here.',
closeOnClickOutside: false,
button: 'ok'
})
localStorage.setItem('modalTimestamp', currentTime.getTime());
}
}
}