1.创建cooKie()
function setCookie(key, val, time) {
var date = new Date();
date.setDate(date.getDate() + time);
document.cookie = `${key}=${val};expires=${date}`;
}
调用cookie示例
setCookie('name', '张三');
setCookie('age', 20, 1);
2
// 获取getCookie()
// 根据key 获取对应的cookie值
function getCookie(key) {
var arry = document.cookie.split('; ');
for (var item of arry) {
var newArry = item.split('=');
if (newArry[0] == key) {
return newArry[1];
}
}
}
调用示例
var result2 = getCookie('age');
if (!result) {
result2 = 'cookie值不存在';
}
3.删除Cookie
// removeCookie() --- 删除Cookie
function removeCookie(key_) {
this.setCookie(key_, '', -1)
}
示例代码:
removeCookie('name');
4.清空cookie
// 清空cookie
function clearCookie() {
var arry = document.cookie.split('; ');
for (var item of arry) {
var newArry = item.split('=');
console.log(newArry[0]);
// this.setCookie(newArry[0], '', -1);//一种方法
this.removeCookie(newArry[0]);
}
}
调用示例
clearCookie();