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

Sph*_*hvn 22 cookies jquery jquery-cookie

我想要:

  1. 检查是否存在名称为"query"的cookie
  2. 如果是,那么什么也不做
  3. 如果不是,请创建值为1的cookie"query"

注意:我使用的是jQuery 1.4.2和jQuery cookie插件.

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

Jac*_*kin 49

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

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

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

那么你只需要在你的客户端代码中写这个:

$.lazyCookie('query', '1', {expires:7, path:'/'});
Run Code Online (Sandbox Code Playgroud)

  • 请注意,==与===(或!= vs!==)不同. (3认同)
  • 我认为`!=`应该是`==`:p (2认同)

Rei*_*gel 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.
Run Code Online (Sandbox Code Playgroud)

你还想要什么?


Col*_*con 6

类似于雅各布斯的答案,但我更喜欢测试undefined.

if($.cookie('query') == undefined){
    $.cookie('query', 1, { expires: 1 });
}
Run Code Online (Sandbox Code Playgroud)