代码之家  ›  专栏  ›  技术社区  ›  Sphvn Frebin Francis

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

  •  22
  • Sphvn Frebin Francis  · 技术社区  · 15 年前

    我想:

    1. 检查是否存在名为“query”的cookie
    2. 如果是,那就什么也不做
    3. 如果没有,则创建一个值为1的cookie“查询”。

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

    有人对我该怎么做有什么建议吗?

    3 回复  |  直到 13 年前
        1
  •  49
  •   Jacob Relkin    13 年前
    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:'/'});
    
        2
  •  6
  •   Reigel Gallarde    15 年前

    这个??

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

    你还想要什么??

        3
  •  6
  •   Colin Bacon    13 年前

    类似于雅各布斯的答案,但我更喜欢测试未定义的。

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