pCookie.js
(function(){ var PotatogCookie = {}; //设置cookie PotatogCookie.set = function(key, value, delay) { //默认cookie为七天之后过期 3s 4m 5h 7d 秒 分 时 天 if(delay == "undefined")delay = "7d"; delay = delay.toLowerCase(); var expireDate = new Date(); var num = parseInt(delay); if(delay.indexOf("d") !== -1) { expireDate.setDate(expireDate.getDate() + num); } else if(delay.indexOf("h") !== -1) { expireDate.setHours(expireDate.getHours() + num); } else if(delay.indexOf("m") !== -1) { expireDate.setMinutes(expireDate.getMinutes() + num); } else if(delay.indexOf("s") !== -1) { expireDate.setSeconds(expireDate.getSeconds() + num); } else { expireDate.setDate(expireDate.getDate() + num); } if(typeof value == "object") { value = JSON.stringify(value); } value = escape(value); document.cookie = key + "=" + value + ";expires=" + expireDate.toGMTString(); return this.get(key); } //得到cookie 如果不存在 返回 undefined PotatogCookie.get = function(key) { var objCookie = {}; var cookie = document.cookie; var keyValueList = cookie.split(";"); for(var index in keyValueList) { var keyValue = keyValueList[index].split("="); var k = keyValue[0].trim(); var v = keyValue[1];
v = unescape(v); v = this.decodeJson(v); objCookie[k] = v; } if(typeof key == "undefined") { return objCookie; } return objCookie[key]; } //删除cookie PotatogCookie.del = function(key) { //删除所有cookie if(typeof key == "undefined") { var cookieList = this.get(); for(key in cookieList) { this.del(key); } return true; } else { if(this.get(key) == "undefined") { return false; } else { return this.set(key,'',"0s"); } } } PotatogCookie.decodeJson = function(value) { //数组转成的对象字符串 var regAryStr = /^[[s|S]*]$/; //对象转成的对象字符串 var regObjStr = /^{(["s|S]+":"[s|S]*)+"}$/; if(regAryStr.test(value)) { return eval("(" + value + ")"); } if(regObjStr.test(value)) { return JSON.parse(value); } return value; } window.pCookie = PotatogCookie; })(window);
demo.html
使用方式
设置cookie
pCookie.set("name","张三","7d");
读取cookie 如果不存在 返回undefined
var name = pCookie.get("name");不传参表示获得所有
删除cookie
pCookie.del("name");不传参表示删除所有