javascript - Cookie 每 30 天显示一个弹出窗口

标签 javascript jquery cookies

<script type="text/javascript">
jQuery(document).ready(function(){
if (document.cookie.indexOf('visited=false') == -1)
{
var fifteenDays = 1000*60*60*24*30;
var expires = new Date((new Date()).valueOf() + fifteenDays);
document.cookie = "visited=true;expires=" + expires.toUTCString();
$.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
}
});
</script>

我上面的代码有什么问题,每次在我的博客中加载页面时都会调用类似 facebook 的弹出窗口。我只是每 30 天只显示一次。我该怎么做?

最佳答案

您的特定实现看起来像是让您检查 cookie 中的 'visited=false',但将 cookie 设置为 'visited=true' 所以您的 if 语句永远不会匹配。


我建议您使用一组经过验证的 cookie 操作函数,然后您的任务就会非常简单。

以下是当我的环境还没有 cookie 功能时我使用的 cookie 功能:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

一旦你有了这些,你就可以这样做:

jQuery(document).ready(function() {
    var visited = readCookie('visited');
    if (!visited || visited !== "true") {
        createCookie('visited', "true", 30);
        $.colorbox({width:"400px", inline:true, href:"#exestylepopups"});
    }
});

关于javascript - Cookie 每 30 天显示一个弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12926119/

相关文章:

javascript - 使用 js-cookie 设置 cookie 过期时间

javascript - 检查字符串的第一个字符是否为数字会报错,表明 charat 不是有效方法

javascript - 文件夹路径 - 绝对文件夹路径

javascript - 滚动浏览彼此堆叠的 div

javascript - 找到真正的父元素

Javascript 内联函数调用

windows - 在 Internet Explorer 中以编程方式设置 cookie

javascript - css 动画不适用于新的 dom 元素

javascript - 将元素拖动到可排序后切换停止工作

javascript - cookies 的替代品