一、cookie的设置
//添加cookie
document.cookie = ‘name = mashuai‘;
//读取cookie
console.log(document.cookie);
//修改cookie
document.cookie = ‘name = zhangsan‘;
//设置时间
var oDate = new Date();
oDate.setDate(oDate.getDate()+1);
//document.cookie = ‘name=mashuai; expires =‘+oDate;
//设置域名 domain
document.cookie = ‘name = mashuai;expires=‘+oDate+‘domain=loclhost‘;
//设置路径 path
document.cookie=‘name=lisi; expires=‘+oDate+‘; path=/‘;
//中文编码
document.cookie=‘name=‘+encodeURIComponent(‘王麻子‘);
console.log(decodeURIComponent(document.cookie));
二、cookie函数的封装
//添加和修改
function setCookie(name,value,days,path){
days = days || 0;
path = path || ‘/‘;
var oDate = new Date();
oDate.setDate(oDate.getDate()+days);
document.cookie = name + ‘=‘+ encodeURIComponent(value)+‘;expires=‘+oDate+‘;path=‘+path;
}
//获取cookie
function getCookie(name){
var aCookie = document.cookie.split(‘; ‘);
for(var i=0;i<aCookie.length;i++){
var temp = aCookie[i].split(‘=‘);
if(temp[0]===name){
return decodeURIComponent(temp[1]);
}
}
}
//删除cookie
function removeCookie(name,path){
document.cookie = name + ‘=;expires=-1;path=‘+path;
}