小编典典

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

all

如何使用 jQuery 设置和取消设置 cookie,例如创建一个名为 cookie 并将test值设置为1


阅读 135

收藏
2022-02-25

共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 将成为会话 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 版本。显然,原来的插件并没有去任何地方。

2022-02-25