如何使用 jQuery 设置/取消设置 cookie? [英] How do I set/unset a cookie with jQuery?

查看:30
本文介绍了如何使用 jQuery 设置/取消设置 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

2019 年 4 月更新

cookie 读取/操作不需要 jQuery,所以不要使用下面的原始答案.

jQuery isn't needed for cookie reading/manipulation, so don't use the original answer below.

转到https://github.com/js-cookie/js-cookie 而是使用不依赖于 jQuery 的库.

Go to https://github.com/js-cookie/js-cookie instead, and use the library there that doesn't depend on jQuery.

基本示例:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => // => 'value'

有关详细信息,请参阅 github 上的文档.

See the docs on github for details.

2019 年 4 月之前(旧)

查看插件:

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");

更新(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆