项目描述
上传时间
浏览人数
1-增
setCookie(Name,Value,Days)
let u={city:"Toyko",area:"Fujiyama"}
setCookie("sakura",JSON.stringify(u),1) //转换成字符串
function setCookie(Name,Val,Days) {
if (Name && Val && Days){
Name=Name.replace(/\s+/g,"") //去掉所有空格
Val=Val.trim() //去掉前后空格
let date=new Date();
console.log(date);
let t=date.getTime()+Days*24*60*60*1000
date.setTime(t)
console.log(date);
let utc=date.toUTCString()
console.log(utc);
document.cookie=Name+"="+Val+";expires="+utc+";path=/" //消失时间
}
}
2-删
将时间变为0就没有了,Name,Value,Days,但三者不能为空值,空值则无意义,Days为0需条件取有值的做判定条件,Days为负数,则可以正常删除
let u={city:"Toyko",area:"Fujiyama"}
setCookie("sakura",JSON.stringify(u),1) //转换成字符串
function setCookie(Name,Val,Days) {
if (Name && Val && Days){
Name=Name.replace(/\s+/g,"") //去掉所有空格
Val=Val.trim() //去掉前后空格
let date=new Date();
console.log(date);
let t=date.getTime()+Days*24*60*60*1000
date.setTime(t)
console.log(date);
let utc=date.toUTCString()
console.log(utc);
document.cookie=Name+"="+Val+";expires="+utc+";path=/" //消失时间
}
}
setCookie("sakura",JSON.stringify(u),-1)
3-改
let a={area:"Hokkaido",characteristic:"fish"}
setCookie("sakura",JSON.stringify(a),1)
4-查
let cv = getCookie("sakura");
function getCookie(Name) {
if (!Name) {
return ""; //如果空值则返回空值
}
let arr = document.cookie.split("; "); //分割cookie
Name += "=";
for (let i = 0; i < arr.length; i++) { //循环查找
if(arr[i].startsWith(Name)){
return arr[i].substring(Name.length);
}
}
return ""; //如果循环未找到则返回空值
}
console.log(cv);