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


当前回答

我知道有很多很好的答案。通常,我只需要读取cookie,不希望通过加载额外的库或定义函数来增加开销。

下面是如何在一行javascript中读取cookie。我在Guilherme Rodrigues的博客文章中找到了答案:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

这读取cookie命名为key,漂亮,干净和简单。

其他回答

你可以在Mozilla网站上使用这个库

你可以像这样设置和获取饼干

docCookies.setItem(name, value);
docCookies.getItem(name);

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版本相同的功能和通用语法。显然,原来的插件并没有去任何地方。

我知道,已经有很多答案了,但这里有一个设置,获取和删除所有漂亮的香草,并很好地放入全局引用:

window.cookieMonster = window.cookieMonster || 
    {
        // https://stackoverflow.com/a/25490531/1028230
        get: function (cookieName) {
            var b = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
            return b ? b.pop() : '';
        },

        delete: function (name) {
            document.cookie = '{0}=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
                .replace('{0}', name);
        },

        set: function (name, value) {
            document.cookie =
                '{0}={1};expires=Fri, 31 Dec 9999 23:59:59 GMT;path=/;SameSite=Lax'
                .replace('{0}', name)
                .replace('{1}', value);
        }
    };

请注意,cookie getting regex是从另一个城堡的一个问题的答案中截取的。


我们来测试一下:

cookieMonster.set('chocolate', 'yes please');
cookieMonster.set('sugar', 'that too');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

cookieMonster.delete('chocolate');

console.log(cookieMonster.get('chocolate'));
console.log(document.cookie);

如果你在尝试之前没有任何饼干,应该给你…

yes please
chocolate=yes please; sugar=that too

sugar=that too

请注意,饼干持续的时间不长,但从我们的角度来看,基本上是这样的。通过查看这里的字符串或其他答案,您可以很容易地了解如何更改日期。

下面是如何使用JavaScript设置cookie:

以下代码摘自https://www.w3schools.com/js/js_cookies.asp

函数setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires=" expires="+ d.toUTCString(); 文件中。cookie = cname + "=" + cvalue + ";"+ expires + ";path=/"; }

现在你可以使用下面的函数获取cookie:

function getCookie(cname) { var 名称 = 别名 + “=”; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0, i <ca.length, i++) { var c = ca[i]; 而 (c.charAt(0) == ' ') { c = c.子字符串(1); } if (c.indexOf(name) == 0) { 返回 c.substring(name.length, c.length); } } 返回 “”; }

最后,这是检查cookie的方法:

函数checkCookie() { var username = getCookie("username"); If(用户名!= ""){ alert(“欢迎再次光临”+用户名); }其他{ username = prompt("请输入您的姓名:",""); If (username != "" && username != null) { setCookie("username", username, 365); } } }

如果你想删除cookie,只需将expires参数设置为一个经过的日期:

document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";

我知道有很多很好的答案。通常,我只需要读取cookie,不希望通过加载额外的库或定义函数来增加开销。

下面是如何在一行javascript中读取cookie。我在Guilherme Rodrigues的博客文章中找到了答案:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

这读取cookie命名为key,漂亮,干净和简单。