const cookie = (function () {
//cookie的格式
// name=value;expires=有效时间;path=路径;domian=域名;secure 安全 https
//1.设置cookie
function setCookie(name, value, days, path, domian, secure) {
var strCookie = '';
if (name) {
strCookie += name + "=" + value + ";";
}
if (typeof (days) === "number") {
var date = new Date();
date.setDate(date.getDate() + days);
strCookie += "expires=" + date + ";"
}
if (path) {
strCookie += "path=" + path + ";"
}
if (domian) {
strCookie += "domian=" + domian + ";"
}
if (secure) {
strCookie += "secure";
}
document.cookie = strCookie;
}
//2.获取cookie
function getCookieAll() {
var data = {};
var strCookie = document.cookie; // age=20; name=周杰伦
var arr = strCookie.split("; "); //[age=20] [name=周杰伦]
arr.forEach(function (el) {
var list = el.split("="); // [age,20] [name,周杰伦]
data[list[0]] = list[1];
})
return data;
}
//3.通过指定的名称获取cookie值
function getCookieByName(name) {
var data = getCookieAll(); //返回是一个对象
return data[name];
}
//4.封装 删除cookie
function removeCookie(name) {
setCookie(name, "", -1);
}
//暴露方法
return {
setCookie,//设置
getCookieByName,//获取
removeCookie//删除
}
})();
网友评论