【问题标题】:Cookie to show a popup every 30 daysCookie 每 30 天显示一个弹出窗口
【发布时间】:2012-10-17 16:01:05
【问题描述】:
<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 天只显示一次。我该怎么做?

【问题讨论】:

    标签: javascript jquery cookies


    【解决方案1】:

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


    我建议您使用一组经过验证的 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"});
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多