2019独角兽企业重金招聘Python工程师标准>>>
设置cookie的保存时间,通过cookie的expires性质指定一个终止时间就可以了。也就是说,你在设置cookie的时候,你的cookie字串要像下面这样组合:
var d= new Date(); d.setHours(d.getHours() + (24 * 30)); //保存一个月 document.cookie = "visited=yes; expires=" + d.toGMTString(); 这样你的cookie就能保存一个月了,下面是我测试用的代码,你自己看看是否有其他帮助,有的话尽管拿去:
function Window_Load(){
setCookie("name","111"); //临时cookie
setCookie("age","222",24 * 7); //保存7天
setCookie("address","333",24,"/"); //保存1天,path为根目录
//设定cookie为安全的(secure=true),只能在HTTPS或与其他安全协议
//连接在一起的时候才被传输
setCookie("phone","444",24,"/",".",false);
alert(document.cookie);
alert(getCookie("age"));
//删除名称为"age"的cookie
removeCookie("age")
alert(document.cookie);
//删除名称为"address"的cookie,因为设置时设定的path,所以删除
//时也需要传入对应path
removeCookie("address","/")
alert(document.cookie);
}
function setCookie(name,value,hours,path,domain,secure){
var cdata = name + "=" + value;
if(hours){
var d = new Date();
d.setHours(d.getHours() + hours);
cdata += "; expires=" + d.toGMTString();
}
cdata +=path ? ("; path=" + path) : "" ;
cdata +=domain ? ("; domain=" + domain) : "" ;
cdata +=secure ? ("; secure=" + secure) : "" ;
document.cookie = cdata;
}
function getCookie(name){
var reg = eval("/(?:^|;\\s*)" + name + "=([^=]+)(?:;|$)/");
return reg.test(document.cookie) ? RegExp.$1 : "";
}
function removeCookie(name,path,domain){
this.setCookie(name,"",-1,path,domain);
}