简体   繁体   English

将JavaScript Cookie分配给变量

[英]assign JavaScript cookie to a variable

I am trying to assign a js cookie to a variable so that I can check if that cookie has been set or not: 我正在尝试将js cookie分配给变量,以便我可以检查该cookie是否已设置:

(function(){
     var cookieSet = document.cookie ='cookie1=test';

     if (cookieSet == null) {
          console.log('hide');
     }
     if (cookieSet) {
         console.log('show');
          HB.BestBreakfast.showPanelAndHideOthers("commentBox");
     }

})();

however it's always showing 'show'. 但是它总是显示“显示”。

Where am I wrong? 我哪里错了?

var cookieSet = document.cookie ='cookie1=test';

This line assigns a value to document.cookie , then it assigns that value to cookieSet . 该行将一个值分配给document.cookie ,然后将该值分配给cookieSet

This means that cookieSet will always have a value. 这意味着cookieSet始终具有一个值。

Perhaps you want something like: 也许您想要这样的东西:

var cookieSet = document.cookie;
document.cookie ='cookie1=test';

So cookieSet gets the old value of document.cookie and then you assign a new value. 因此cookieSet获取document.cookie值, 然后分配一个新值。


Additionally, if there are no cookies set, then document.cookie will be an empty string and not null . 此外,如果未设置cookie,则document.cookie将为空字符串 ,而不为null

You need to change your test to: 您需要将测试更改为:

if (cookieSet == "") {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM