如何删除饼干?

2022-08-29 23:23:25

我创建 Cookie 的功能是否正确?如何在程序开始时删除 Cookie?有没有简单的编码?

function createCookie(name,value,days)
function setCookie(c_name,value,1) {
  document.cookie = c_name + "=" +escape(value);
}

setCookie('cookie_name',mac);

function eraseCookie(c_name) {
  createCookie(cookie_name,"",-1);
}

答案 1

试试这个:

function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}

您可以这样定义:get_cookie()

function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}

答案 2

这里有一个关于Quirksmode的好链接。

function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}