创建一个cookie,如果(且仅当)它不存在
-
26-09-2019 - |
题
<强>我需要:强>
- 来看看检查是否与“查询”名称的cookie存在
- 如果是的话,什么也不做
- 如果没有,创建cookie“询问”以1:1的值 醇>
注意:我使用jQuery 1.4.2和 jQuery的饼干插件
没有任何人有任何建议,我怎么能这样做呢?
解决方案
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:'/'});
其他提示
此??
$.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 });
}
不隶属于 StackOverflow