乐趣区

关于javascript:Javascript操作cookieaddCookiegetCookieclearAllCookie等操作

JavaScript 对 Cookies 的操作,JS 对 Cookie 做增删改查。
删除所有 cookie

function clearAllCookie() {document.cookie.split(";").forEach(function (c) {document.cookie = c.replace(/^ +/, "").replace(/=.*/,"=;expires="+ new Date().toUTCString() +";path=/");
    });
};

获取 Cookie

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(";");
    for (var i = 0; i < ca.length; i++) {var c = ca[i];
        while (c.charAt(0) == " ") {c = c.substring(1)
        }
        if (c.indexOf(name) == 0) {return c.substring(name.length, c.length)
        }
    }
    return ""
};

增加 Cookie

function createCookie(name, value, days, path) {
    path = path || "/";
    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=" + path
};

删除 Cookie

function deleteCookie(name) {var expires = new Date();
    expires.setTime(expires.getTime()-1);
    document.cookie = name + "=;expires=" + expires.toUTCString()};
退出移动版