如何使用jQuery设置/取消设置cookie? [英] How do I set/unset a 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)的超时:
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' });
更新(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 the 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屋!