【发布时间】:2011-02-18 22:08:35
【问题描述】:
我想:
- 检查是否存在名为“query”的 cookie
- 如果是,则什么也不做
- 如果否,则创建一个值为 1 的 cookie“查询”
注意:我使用的是 jQuery 1.4.2 和 jQuery cookie plugin。
有人对我如何做到这一点有任何建议吗?
【问题讨论】:
标签: jquery cookies jquery-cookie
我想:
注意:我使用的是 jQuery 1.4.2 和 jQuery cookie plugin。
有人对我如何做到这一点有任何建议吗?
【问题讨论】:
标签: jquery cookies 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:'/'});
【讨论】:
!= 应该是== :p
这个??
$.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.
你还想要什么??
【讨论】:
类似于 Jacobs 的回答,但我更喜欢测试未定义。
if($.cookie('query') == undefined){
$.cookie('query', 1, { expires: 1 });
}
【讨论】:
null 现已弃用,必须使用 undefined。