我需要一个cookie或本地存储解决方案



我希望这个window.onload每月只触发一次模态,但我很难让它工作-请帮助

<script type="text/javascript">
window.onload = function () {
OpenBootstrapPopup();
};
function OpenBootstrapPopup() {
$("#simpleModal").modal('show');
}
function myFunctionClose() {
$("#simpleModal").modal('hide');
}        
</script>

其实很简单。您可以在上次弹出窗口出现时保存在本地存储中。但要注意一些细节:本地存储只保存文本,所以要保存日期,可以保存时间戳。

它看起来像这样:

<script type="text/javascript">
window.onload = function () {
OpenBootstrapPopupIfOneMonthHasPassed();
};

function OpenBootstrapPopupIfOneMonthHasPassed() {   
let lastTimeModalWasOpened = localStorage.getItem("lastTimeModalOpened");
// if has never opened, then open it 
if (!lastTimeModalWasOpened) {
return openModal();
}
// we need to convert it back to date object
let dateObjectlastTimeModalWasOpened = new Date(parseInt(lastTimeModalWasOpened));
// we substract the dates and get their difference in miliseconds. If you want to check if the month has changed instead of a fixed amount of days, you could compare the Date.month property or something else
let timePassedSinceModalWasOpened = new Date() - dateObjectlastTimeModalWasOpened;
// the difference is given in miliseconds, thus we need to divide in milisecons, seconds, minutes, hours, days
if (timePassedSinceModalWasOpened / (1000 * 60 * 60 * 24 * 30) > 30) {
return openModal();
}
}
function openModal() {
$("#simpleModal").modal('show');
localStorage.setItem("lastTimeModalOpened", Date.now());
}
</script>

最新更新