将Cookie设置为仅显示弹出窗口

时间:2015-06-17 09:38:40

标签: javascript jquery cookies

我正在尝试设置一个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中时加载,我只需要显示一次。我怎么能这样做?

2 个答案:

答案 0 :(得分:4)

您可以使用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);
}

答案 1 :(得分: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