javascript - 如何使用 jQuery 设置/取消设置 cookie?

标签 javascript jquery dom cookies

如何使用 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/

相关文章:

javascript - HTMLCollections 可以用 for...of (Symbol.iterator) 迭代吗?

javascript - AIM 7 使用 .aba 文件 - 需要将其解压

javascript - Spotify API 对 api/ token 授权的错误请求错误 : 400

javascript - 我怎样才能在 Devtools Extension 上只捕获 XHR 请求?

jquery - 先播放 GIF 的一部分,然后无限循环某一部分

javascript - Bootstrap 表单动态添加删除带有字段的表单

javascript - .toLocaleDateString() 是否根据位置自动格式化日期?

php - 如何使用 jquery 根据选择下拉列表显示文本区域?

jquery - 如何使用 jQuery 根据链接的 href 通过 ID 获取元素?

javascript - Jquery 链接选择任何线索我做错了什么?