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()
};
版权声明:程序员胖胖胖虎阿 发表于 2022年9月13日 上午5:16。
转载请注明:Javascript操作cookie,addCookie,getCookie,clearAllCookie等操作 | 胖虎的工具箱-编程导航
转载请注明:Javascript操作cookie,addCookie,getCookie,clearAllCookie等操作 | 胖虎的工具箱-编程导航
相关文章
暂无评论...