如果(并且仅当)它尚不存在,则创建一个cookie

时间:2010-05-13 01:56:17

标签: jquery cookies jquery-cookie

我想:

  1. 检查名称为“query”的cookie是否存在
  2. 如果是,则不做任何事
  3. 如果不是,请创建值为“
  4. ”的Cookie“查询”

    注意:我使用的是jQuery 1.4.2和jQuery cookie plugin

    有没有人对我如何做到这一点有任何建议?

3 个答案:

答案 0 :(得分:49)

if($.cookie('query') === null) { 
    $.cookie('query', '1', {expires:7, path:'/'});
}

或者,您可以为此编写一个包装函数:

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

然后你只需要在你的客户代码中写这个:

$.lazyCookie('query', '1', {expires:7, path:'/'});

答案 1 :(得分:6)

此??

$.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.

你还想要什么?

答案 2 :(得分:6)

类似于Jacobs的答案,但我更喜欢测试未定义的。

if($.cookie('query') == undefined){
    $.cookie('query', 1, { expires: 1 });
}
相关问题