显示基于 Javascript 个 Cookie 的内容

Showing Content Based on Javascript Cookies

我正在尝试创建一个基于 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 不存在,它将 return 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();
});