如何使用 jQuery 设置和取消设置 cookie,例如创建一个名为 test
的 cookie 并将值设置为 1
?
最佳答案
2019 年 4 月更新
cookie 读取/操作不需要 jQuery,所以不要使用下面的原始答案。
转到 https://github.com/js-cookie/js-cookie而是使用不依赖 jQuery 的库。
基本示例:
// Set a cookie
Cookies.set('name', 'value');
// Read the cookie
Cookies.get('name') => // => 'value'
详情请参阅 github 上的文档。
2019 年 4 月之前(旧)
查看插件:
https://github.com/carhartl/jquery-cookie
你可以这样做:
$.cookie("test", 1);
删除:
$.removeCookie("test");
另外,要在 cookie 上设置一定天数(这里是 10 天)的超时时间:
$.cookie("test", 1, { expires : 10 });
如果省略 expires 选项,则 cookie 成为 session cookie,并在浏览器退出时被删除。
涵盖所有选项:
$.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 的值:
var cookieValue = $.cookie("test");
更新(2015 年 4 月):
正如以下评论中所述,开发原始插件的团队已在一个新项目 (https://github.com/js-cookie/js-cookie) 中删除了 jQuery 依赖项,该项目具有与 jQuery 版本相同的功能和通用语法。显然原来的插件并没有去任何地方。
关于javascript - 如何使用 jQuery 设置/取消设置 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1458724/