【问题标题】:Create a cookie if (and only if) it doesn't already exist当(且仅当)它不存在时创建一个 cookie
【发布时间】:2011-02-18 22:08:35
【问题描述】:

我想:

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

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

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

【问题讨论】:

    标签: jquery cookies jquery-cookie


    【解决方案1】:
    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】:

    这个??

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

    你还想要什么??

    【讨论】:

    • @Ozaki - 我猜你误解了它......我试图展示的是可能的选择......我很高兴你现在解决了它...... :) 干杯!
    【解决方案3】:

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

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

    【讨论】:

    • 随着脚本的最新更新,null 现已弃用,必须使用 undefined
    • 你为什么说'null'现在已经被弃用了?我无法在网上找到任何支持材料。见here
    猜你喜欢
    • 2011-04-12
    • 1970-01-01
    • 2011-05-05
    • 2019-07-12
    • 2012-06-14
    • 2012-06-02
    • 2022-01-01
    • 2016-08-24
    相关资源
    最近更新 更多