JavaScript设置、获取、清除单值和多值cookie的方法
废话不多说了,直接给大家贴代码了。
具体代码如下:
varCookieUtil=(function(){
varCookie=function(){
//获取单值cookie
this.get=function(name){
varstart=document.cookie.indexOf(encodeURIComponent(name));
varend=document.cookie.indexOf(';',start);
if(end==-){
end=document.cookie.length;
}
returndecodeURIComponent(document.cookie.substring(start+name.length+,end));
};
//设置单值cookie
this.set=function(name,value,expires,path,domain,secure){
varcookieText=encodeURIComponent(name)+"="+encodeURIComponent(value);
//设置默认过期时间为七天
if(expires==undefined){
vardate=newDate();
date.setTime(date.getTime()+****);
expires=date;
}
if(expiresinstanceofDate){
cookieText+=";expires="+expires.toGMTString();
}
if(path!=undefined){
cookieText+=";path="+path;
}
if(domain!=undefined){
cookieText+=";domain"+domain;
}
if(secure!=undefined){
cookieText+=";secure";
}
document.cookie=cookieText;
};
//清除单值cookie
this.unset=function(name,path,domain,secure){
this.set(name,'',newDate(),path,domain,secure);
};
//设置多值cookie
this.setAll=function(name,subCookies,expires,path,domain,secure){
varcookieText=";"+encodeURIComponent(name)+"=",
arr=newArray();
for(varattrinsubCookies){
arr.push([encodeURIComponent(attr)]+":"+encodeURIComponent(subCookies[attr]));
}
this.set(name,arr.join('&'),expires,path,domain,secure);
};
//获取多值cookie
this.getAll=function(name){
varobj={};
vararr=this.get(name).split('&');
for(vari=,len=arr.length;i<len;i++){
vartmpArr=arr[i].split(':');
obj[decodeURIComponent(tmpArr[])]=decodeURIComponent(tmpArr[]);
}
returnobj;
};
//获取多值cookie的子cookie
this.getSub=function(name,subname){
varobj=this.getAll(name);
returnobj[subname];
};
//清除指定的多值cookie
this.unsetAll=function(name,path,domain,secure){
this.unset(name,'',newDate(),path,domain,secure);
};
//清除指定多值cookie的子cookie
this.unsetSub=function(name,subname,path,domain,secure){
varobj=this.getAll(name);
deleteobj[subname];
this.setAll(name,obj,null,path,domain,secure);
};
};
returnnewCookie();
})();
以上代码就是本文给大家介绍JavaScript设置、获取、清除单值和多值cookie的方法,有哪里不清楚的地方欢迎给我留言。