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

我想要:

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

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

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

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:'/'}); 

类似于Jacobs的回答,但我更喜欢测试undefined。

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

这个??

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

你还想要什么?