【问题标题】:Setting a cookie to only show popup once将 cookie 设置为仅显示一次弹出窗口
【发布时间】:2015-06-17 09:38:39
【问题描述】:

我正在尝试设置一个 cookie 只显示一次弹出窗口,这是我目前的代码:

jQuery(window).load(function(){
    // Load pop up within parent-page section only
    if (window.location.href.indexOf('parent-page') > -1) {

        alert("your url contains the parent-page in the URL");

        $.magnificPopup.open({
            items: [
                {
                    src: '#disclaimer', // CSS selector of an element on page that should be used as a popup
                    type: 'inline'
                }
            ],
            removalDelay: 300,
            mainClass: 'mfp-fade',
            closeOnContentClick: false,
            modal: true
        });
    }
});

目前每次父页面在 URL 中时都会加载,我只需要显示一次。我该怎么做?

【问题讨论】:

  • 正如您所说,将看到的状态存储在 cookie 或本地存储中!你有沿着这条路的一些代码吗?
  • 取决于您希望它不出现在当前会话还是 x 天?

标签: javascript jquery cookies


【解决方案1】:

您可以使用jQuery cookie plugin 来实现:

if (window.location.href.indexOf('parent-page') > -1 && !$.cookie('popup-shown')) {
    $.magnificPopup.open({
        items: [
            {
                src: '#disclaimer', // CSS selector of an element on page that should be used as a popup
                type: 'inline'
            }
        ],
        removalDelay: 300,
        mainClass: 'mfp-fade',
        closeOnContentClick: false,
        modal: true
    });
    $.cookie('popup-shown', true);
}

【讨论】:

  • 感谢您的回答。由于这使用了一个插件,我确信它效果很好,如果我可以像其他答案所建议的那样使用本地存储来实现这一点,我不会特别喜欢将另一个插件加载到我的网站上。
  • 是的,@Tushar 的回答也可以。请注意,如果您想避免使用其他插件,您可以使用 these functions 使用本机 JS 自己获取/设置 cookie。
【解决方案2】:

你可以使用localStorage:

jQuery(window).load(function () {
    if (window.location.href.indexOf('parent-page') > -1 && !localStorage.getItem('popup_show')) {

        $.magnificPopup.open({
            items: [{
                src: '#disclaimer', // CSS selector of an element on page that should be used as a popup
                type: 'inline'
            }],
            removalDelay: 300,
            mainClass: 'mfp-fade',
            closeOnContentClick: false,
            modal: true
        });

        localStorage.setItem('popup_show', 'true'); // Set the flag in localStorage
    }
});

localStorage 属性允许您访问本地存储对象。 localStorage 类似于 sessionStorage。唯一的区别是,虽然存储在 localStorage 中的数据没有过期时间,但存储在 sessionStorage 中的数据会在浏览会话结束时被清除——即浏览器关闭时。

文档:https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

【讨论】:

  • 这很好用有没有办法可以设置 cookie 在 10 天内过期?
  • @egr103 No. localStorage 没有过期日期
猜你喜欢
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-26
  • 2017-10-15
  • 1970-01-01
  • 2019-03-27
相关资源
最近更新 更多