jQuery check if Cookie exists, if not create it

后端 未结 5 631
春和景丽
春和景丽 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: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!

提交回复
热议问题