jQuery check if Cookie exists, if not create it

后端 未结 5 629
春和景丽
春和景丽 2020-12-02 20:27

I cannot get this code to work I must be missing something pretty simple. I am trying to check to see if a Cookie exists, if it does {do nothing} if it doesn\'t {create it}

相关标签:
5条回答
  • 2020-12-02 20:42
     $(document).ready(function() {
    
         var CookieSet = $.cookie('cookietitle', 'yourvalue');
    
         if (CookieSet == null) {
              // Do Nothing
         }
         if (jQuery.cookie('cookietitle')) {
              // Reactions
         }
     });
    
    0 讨论(0)
  • 2020-12-02 20:50

    Try this very simple:

                var cookieExist = $.cookie("status");
                if(cookieExist == "null" ){
                    alert("Cookie Is Null");
    
                }
    
    0 讨论(0)
  • 2020-12-02 20:59

    I think the bulletproof way is:

    if (typeof $.cookie('token') === 'undefined'){
     //no cookie
    } else {
     //have cookie
    }
    

    Checking the type of a null, empty or undefined var always returns 'undefined'

    Edit: You can get there even easier:

    if (!!$.cookie('token')) {
     // have cookie
    } else {
     // no cookie
    }
    

    !! will turn the falsy values to false. Bear in mind that this will turn 0 to false!

    0 讨论(0)
  • 2020-12-02 21:01

    You can set the cookie after having checked if it exists with a value.

     $(document).ready(function(){            
          if ($.cookie('cookie')) { //if cookie isset
             //do stuff here like hide a popup when cookie isset
             //document.getElementById("hideElement").style.display = "none";
          }else{
             var CookieSet = $.cookie('cookie', 'value'); //set cookie
          }       
     });
    
    0 讨论(0)
  • 2020-12-02 21:03

    I was having alot of trouble with this because I was using:

    if($.cookie('token') === null || $.cookie('token') === "")
    {
          //no cookie
    }
    else
    {
         //have cookie
    }
    

    The above was ALWAYS returning false, no matter what I did in terms of setting the cookie or not. From my tests it seems that the object is therefore undefined before it's set so adding the following to my code fixed it.

    if($.cookie('token') === null || $.cookie('token') === "" 
        || $.(cookie('token') === "null" || $.cookie('token') === undefined)
    {
          //no cookie
    }
    else
    {
         //have cookie
    }
    
    0 讨论(0)
提交回复
热议问题