1.新增Cookie
function setCookie(name, value , time) {
var strSec = getSec(time); //getSec()是封装好的获取时间单位的函数
var exp = new Date();
exp.setTime(exp.getTime() + strSec * 1);
name = name.replace(/^\s+|\s+$/g,""); //replace()函数为参数去掉多余的空格
document.cookie = name + "=" + escape(value) + ";expires="+ exp.toGMTString(); //escape()函数编码,防止参数取值出现乱码
}
2.获取Cookie
function getCookie(name) {
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); //获取现存所有Cookie
if(arr=document.cookie.match(reg)){
return (unescape(arr[2])); //unescape()函数解码参数并返回
}else{
return null;
}
}
3.删除Cookie
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
var value = getCookie(name);
if (value != null) {
document.cookie = name + "=" + value + ";expires="+ exp.toUTCString();
}
}
4.getSec()函数
function getSec(str){
var str1 = str.substr(0, str.length - 1); //时间数值
var str2 = str.substr(str.length-1, 1); //时间单位
if (str2 == "s") {
return str1 * 1000;
}
else if (str2 == "m") {
return str1 * 60 * 1000;
}
else if (str2 == "h") {
return str1 * 60 * 60 * 1000;
}
else if (str2 == "d") {
return str1 * 24 * 60 * 60 * 1000;
}
}