<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>存储cookie</button>
<button>获取cookie</button>
<button>存储带时长的cookie</button>
<button>删除cookie</button>
<button>修改cookie</button>
<button>单个cookie</button>
<button>清空所有cookie</button>
<script src="jquery-1.11.3.js"></script>
<script>
$("button").eq(0).click(function () {
cookieTools.setItem({
username:"dabao",
age:12,
location:"文化大厦",
})
});
$("button").eq(1).click(function () {
console.log(cookieTools.getAllCookies());
})
$("button").eq(2).click(function () {
cookieTools.setItem({
name: "dabao",
},10000);
})
$("button").eq(3).click(function () {
cookieTools.removeItem("username")
})
$("button").eq(4).click(function () {
cookieTools.modifyItem("username","白白")
})
$("button").eq(5).click(function () {
console.log(cookieTools.getItem("location"));
})
$("button").eq(6).click(function () {
cookieTools.clear()
})
var cookieTools={
getGMT:function (ms) {
var str=new Date().getTime()+ms;
return new Date(str).toGMTString();
},
setItem:function(json,expiresMS){
for(var k in json){
if(typeof expiresMS!="number"){
document.cookie=`${k}=${json[k]}`
}else{
document.cookie=`${k}=${json[k]}; expires=${this.getGMT(expiresMS)}`;
}
}
},
getAllCookies:function () {
var json={};
if (!document.cookie) return json;
document.cookie.split("; ").forEach(function (item) {
var arr=item.split("=");
json[arr[0]]=arr[1];
})
return json;
},
removeItem:function (key) {
document.cookie=`${key}=any; expires=${this.getGMT(-100000)}`;
return true;
},
modifyItem:function (oldKey,newValue,expiresMS) {
if (this.getAllCookies()[oldKey]==undefined) return false;
if (typeof expiresMS!="number"){
document.cookie=`${oldKey}=${newValue}`;
}else {
document
.cookie=`${oldKey}=${newValue}; expires=${this.getGMT(expiresMS)}`
}
return true;
},
getItem:function (key) {
return this.getAllCookies()[key];
},
clear:function () {
return this.setItem(this.getAllCookies(),-1000)
}
}
</script>
</body>
</html>