如何使用jQuery设置/取消设置cookie? [英] How do I set/unset cookie with jQuery?
问题描述
如何使用jQuery设置和取消设置cookie,例如创建名为 test
的cookie,并将值设置为 1
?
How do I set and unset a cookie using jQuery, for example create a cookie named test
and set the value to 1
?
推荐答案
查看插件:
https://github.com/carhartl/jquery-cookie
您可以执行以下操作:
$.cookie("test", 1);
要删除:
$.removeCookie("test");
此外,要在Cookie上设置特定天数(此处为10)的超时: / p>
Additionally, to set a timeout of a certain number of days (10 here) on the cookie:
$.cookie("test", 1, { expires : 10 });
如果省略expires选项,那么cookie将成为会话cookie,并在浏览器退出。
If the expires option is omitted, then the cookie becomes a session cookie, and is deleted when the browser exits.
覆盖所有选项:
$.cookie("test", 1, {
expires : 10, //expires in 10 days
path : '/', //The value of the path attribute of the cookie
//(default: path of page that created the cookie).
domain : 'jquery.com', //The value of the domain attribute of the cookie
//(default: domain of page that created the cookie).
secure : true //If set to true the secure attribute of the cookie
//will be set and the cookie transmission will
//require a secure protocol (defaults to false).
});
要读回cookie的值:
To read back the value of the cookie:
var cookieValue = $.cookie("test");
如果cookie在当前路径的不同路径上创建,您可能希望指定路径参数:
You may wish to specify the path parameter if the cookie was created on a different path to the current one:
var cookieValue = $.cookie("test", { path: '/foo' });
UPDATE(2015年4月):
如下面的注释所述,原来的插件工作的团队删除了一个新项目中的jquery依赖( https://github.com/js-cookie/js-cookie ),它具有与jquery版本相同的功能和一般语法。显然原始的插件不会去任何地方,但。
As stated in the comments below, the team that worked on the original plugin has removed jquery dependency in a new project (https://github.com/js-cookie/js-cookie) which has the same functionality and general syntax as the jquery version. Apparently the original plugin isn't going anywhere though.
这篇关于如何使用jQuery设置/取消设置cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!