Create a cookie if (and only if) it doesn't already exist

后端 未结 3 2088
遇见更好的自我
遇见更好的自我 2020-12-05 23:51

I want to:

  1. Check to see if a cookie with name of \"query\" exists
  2. If yes, then do nothing
  3. If no, create a cookie \"query\" w
3条回答
  •  一个人的身影
    2020-12-06 00:23

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

    Alternatively, you could write a wrapper function for this:

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

    Then you'd only need to write this in your client code:

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

提交回复
热议问题