Javascript 仅清除特定 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5976912/
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-23 19:43:54  来源:igfitidea点击:

Clearing only specific cookies

javascriptcookies

提问by Varada

How can I clear only two cookies using JavaScript?

如何使用 JavaScript 只清除两个 cookie?

I use the below code to set these cookies.

我使用以下代码来设置这些 cookie。

function setCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays==null) ? "" : ";expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

回答by Gumbo

A cookie is expired if the Expiresparameter value is a date in the past. So just set the value to a date in the past:

如果Expires参数值是过去的日期,则cookie 已过期。所以只需将值设置为过去的日期:

function deleteCookie(c_name) {
    document.cookie = encodeURIComponent(c_name) + "=deleted; expires=" + new Date(0).toUTCString();
}

回答by Shpokas

use the same function setCookie(c_name,value,exdays), passing exdays = -1. That will set expiry date to yesterday.

使用相同的函数 setCookie(c_name,value,exdays),传递 exdays = -1。这会将到期日期设置为昨天。