【问题标题】:Showing Content Based on Javascript Cookies显示基于 Javascript Cookie 的内容
【发布时间】:2016-09-20 18:27:03
【问题描述】:

我正在尝试创建一个基于 JS cookie 的时事通讯部分。我的一切工作正常,但无论 cookie 是否存在都显示内容。我正在使用 JS-cookie 脚本。

我希望此部分仅在用户尚未设置 cookie 时显示。基本上,如果这是他们第一次查看网站或 cookie 过期(30 天)之后。

现在,即使我使用私人浏览器,不同的计算机等,它一直说 cookie 已设置并显示内容。我当前的代码在未设置时有它,因此除非删除 !来自 if 语句。

我正在使用 js-cookie 作为 cookie。可以看codepenhttp://codepen.io/byoungz/pen/YqoxJy

var emailSignup = document.getElementById("tgs-subscribe-bar"),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

$('#tgs-subscribe-bar').hide();


if (Cookies.get('emailsignup') == 'null') {
    if (screenWidth < 768) {
    //code for smaller screens      
    setTimeout(function() {
            $('#tgs-subscribe-bar').slideDown();
    }, 4000);

    } else {
        //code for larger
        setTimeout(function() {
                $('#tgs-subscribe-bar').slideDown();
        }, 1000);
    }

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' });
}

 $('.email-exit').click(function() {     
      $("#tgs-subscribe-bar").slideToggle();
});

【问题讨论】:

  • 你不是在检查cookie是否存在之前设置它吗? Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' });
  • 是的,我注意到了这个错误并更新了代码。将很快发布编辑更新。

标签: javascript cookies js-cookie


【解决方案1】:

如果 cookie 不存在,它会返回 undefined 而不是 string null

试试这个:

    var emailSignup = document.getElementById("tgs-subscribe-bar"),
    screenWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);

$('#tgs-subscribe-bar').hide();


if (!Cookies.get('emailsignup')) {
    if (screenWidth < 768) {
    //code for smaller screens      
    setTimeout(function() {
            $('#tgs-subscribe-bar').slideDown();
    }, 4000);

    } else {
        //code for larger
        setTimeout(function() {
                $('#tgs-subscribe-bar').slideDown();
        }, 1000);
    }

    Cookies.set('emailsignup', 'seenemail', { expires: 30, path: '/' });
}

 $('.email-exit').click(function() {     
      $("#tgs-subscribe-bar").slideToggle();
});

【讨论】:

  • 谢谢!效果很好,我看到了我的错误。
  • @4everYoungz 很高兴您了解问题所在,而不仅仅是复制代码 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-08
  • 1970-01-01
相关资源
最近更新 更多