整理了两种简单的 javascript操作cookie写法,均有三个功能:设置cookie、查询cookie、删除cookie。第一种简单易懂,第二种封装使用方便。原生 js设置cookie。
简单版:
function setCookie(name, value, iDay) {
var oDate = new Date();
oDate.setDate(oDate.getDate() + iDay);
document.cookie = name+'='+value+';expires='+oDate;
}
function getCookie(name) {
var arr = document.cookie.split('; ');
var i = 0;
for(i=0; i<arr.length; i++) {
var arr2 = arr .split('=');
if(arr2[0] == name) {return arr2[1];}
}
return '';
}
function removeCookie(name) {
setCookie(name,'',-1);
}
封装版:
var cookie=new function(){
this.set=function(name,value,hours){
var life=new Date().getTime();
life+=hours*1000*60;
var cookieStr=name+"="+escape(value)+";expires="+new Date(life).toGMTString();
document.cookie=cookieStr;
};
this.get=function(name){
var cookies = document.cookie.split(";");
if(cookies.length>0){
var cookie=cookies[0].split("=");
if(cookie[0]==name) {return unescape(cookie[1]);}
}
return null;
};
this.remove=function(name){
var cookieStr=name+"="+escape('null')+";expires="+new Date().toGMTString();
document.cookie=cookieStr;
};
} |