使用 jquery 删除所有 Cookie 并设置新的

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19470517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:03:10  来源:igfitidea点击:

Delete ALL Cookies with jquery and set new

javascriptjqueryhtmlcookies

提问by yas

What I'm trying to do is when user visits page test.html , to delete cookies from pages he previously visited, like test1.html ,test2.html etc. and set new cookie.

我想要做的是当用户访问页面 test.html 时,从他以前访问过的页面中删除 cookie,如 test1.html 、test2.html 等,并设置新的 cookie。

Is there an easier way to delete all previously set cookies at once (I have 100s of pages to declare one by one every time) with jquery?

是否有一种更简单的方法可以使用 jquery 一次删除所有先前设置的 cookie(我每次都有 100 个页面要一个一个地声明)?

I don't know any other way except to delete one by one and then set new:

除了一一删除然后设置新的之外,我不知道其他任何方法:

$.cookie('test1', 'test1', { expires: -1, path: '/' });//deleting cookies from test1.html
$.cookie('test2', 'test2', { expires: -1, path: '/' });//deleting cookies from test2.html

$.cookie('test', 'test', { expires: 30, path: '/' });//setting new cookies 

Thanks

谢谢

回答by megawac

Following the jquery-cookiespec:

遵循jquery-cookie规范:

1) You call $.cookie() which should return all of the cookies on the current page.
2) Just iterate through and remove as below:

1) 您调用 $.cookie() 应该返回当前页面上的所有 cookie。
2)只需迭代并删除如下:

var cookies = $.cookie();
for(var cookie in cookies) {
   $.removeCookie(cookie);
}

Note: when deleting a cookie, you must pass the exact same path, domain and secure options that were used to set the cookie, unless you're relying on the default options that is.

注意:删除 cookie 时,您必须传递用于设置 cookie 的完全相同的路径、域和安全选项,除非您依赖默认选项。

回答by Neeraj

var cookies = document.cookie.split(";");
for(var i=0; i < cookies.length; i++) {
    var equals = cookies[i].indexOf("=");
    var name = equals > -1 ? cookies[i].substr(0, equals) : cookies[i];
    document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
}

Taken from the questions How to delete all cookies with jquery

取自问题如何使用 jquery 删除所有 cookie

回答by user1763876

Please note that the jquery-cookie spec us no longer maintained, superseded by JS Cookie

请注意,我们不再维护的 jquery-cookie 规范被JS Cookie取代