Create a cookie if (and only if) it doesn't al

2019-01-14 15:51发布

I want to:

  1. Check to see if a cookie with name of "query" exists
  2. If yes, then do nothing
  3. If no, create a cookie "query" with a value of 1

Note: I am using jQuery 1.4.2 and the jQuery cookie plugin.

Does anyone have any suggestions as to how I can do this?

3条回答
干净又极端
2楼-- · 2019-01-14 16:03

Similar to Jacobs answer but I prefer to test for undefined.

if($.cookie('query') == undefined){
    $.cookie('query', 1, { expires: 1 });
}
查看更多
做自己的国王
3楼-- · 2019-01-14 16:07

this??

$.cookie('query', '1'); //sets to 1...
$.cookie('query', null); // delete it...
$.cookie('query'); //gets the value....

if ($.cookie('query') == null){ //Check to see if a cookie with name of "query" exists
  $.cookie('query', '1'); //If not create a cookie "query" with a value of 1.
} // If so nothing.

what more do you want??

查看更多
女痞
4楼-- · 2019-01-14 16:14
if($.cookie('query') === null) { 
    $.cookie('query', '1', {expires:7, path:'/'});
}

Alternatively, you could write a wrapper function for this:

jQuery.lazyCookie = function() {
   if(jQuery.cookie(arguments[0]) !== null) return;
   jQuery.cookie.apply(this, arguments);
};

Then you'd only need to write this in your client code:

$.lazyCookie('query', '1', {expires:7, path:'/'});
查看更多
登录 后发表回答