jQuery 当(且仅当)它不存在时创建一个 cookie
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2824021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a cookie if (and only if) it doesn't already exist
提问by Sphvn
I want to:
我想要:
- Check to see if a cookie with name of "query" exists
- If yes, then do nothing
- If no, create a cookie "query" with a value of 1
- 检查是否存在名称为“query”的 cookie
- 如果是,那么什么都不做
- 如果不是,则创建一个值为 1 的 cookie“查询”
Note: I am using jQuery 1.4.2 and the jQuery cookie plugin.
注意:我使用的是 jQuery 1.4.2 和jQuery cookie 插件。
Does anyone have any suggestions as to how I can do this?
有没有人对我如何做到这一点有任何建议?
回答by Jacob Relkin
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:'/'});
回答by Reigel
this??
这个??
$.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.
what more do you want??
你还想要什么??
回答by Colin Bacon
Similar to Jacobs answer but I prefer to test for undefined.
类似于 Jacobs 的答案,但我更喜欢测试 undefined。
if($.cookie('query') == undefined){
$.cookie('query', 1, { expires: 1 });
}