/*
* cookieStorage API
* @maxage 有效期
* path 做用域
* */
function cookieStorage (maxage, path) { var cookie = (function(){ var cookie = {};
var all = document.cookie; // 获取所有的cookie的信息
// 若是为空字符串就返回空对象
if (all === "")
return cookie;
// 分离出名/值对
var list =all.split("; ");
// 遍历每一个cookie
for(var i = 0; i < list.length; i++) {
var cookie = list[i];
console.log(cookie);
var p = cookie.indexOf("="); // 查找第一个"="符号
var name = cookie.substring(0, p); // 获取cookie的名字
var value = cookie.substring(p + 1); // 获取cookie对应的值
value = decodeURIComponent(value); // 将名值对存储到对象中
if (name === "userId") {
continue;
}
cookie[name] = value;
}
return cookie;
}());
// 将全部cookie的名字存储到一个数组中
var keys = [];
for (var key in cookie) keys.push(key);
// 定义存储API公共的属性和方法
// 存储的cookie的个数
this.length = keys.length;
console.log(this.length);
//返回第n个cookie的名字,若是n越界则返回null
this.key = function(n) {
if(n < 0 || n > keys.length) {
return null
}
return keys[n];
};
//返回指定名字的cookie值,若是不存在则返回null
this.getItem = function(name) {
return cookie[name] || null;
};
// 存储cookie值
this.setItem = function(key, value) {
if(! (key in cookie)) {
keys.push(key);
this.length++;
}
//将该名/值对数据存储到cookie对象中
cookie[key] = value;
// 开始正式设置cookie
//首先将要存储的cookie的值进行编码同事建立一个 "名字=编码后的值"形式的字符串
var cookie = key + "=" +encodeURIComponent(value);
// 将cookie的属性也加入到该字符串中
if(maxage) cookie += "; max-age=" + maxage;
if(path) cookie += "; path=" + path;
//经过document.cookie属性来设置cookie
document.cookie = cookie;
};
// 删除指定的cookie
this.removeItem = function(key) {
if( ! (key in cookie)) {
return;
}
//从内部维护的cookie组删除指定的cookie
delete cookie[key];
//同时将cookie中的名字也在内部的数组中删除
for( var i=0; i < keys.length; i++) {
if(keys[i] === key) {
keys.splice(i, 1);
break;
}
}
this.length --;
// 经过将该cookie值设置为空字符串以及将有效期设置为0来删除指定的cookie
document.cookie = key + "=; max-age=0";
};
//删除全部的cookie
this.clear = function () {
//循环全部的coolie的名字,并将cookie删除
for(var i = 0; i < keys.length; i++ )
document.cookie = keys[i] + "=; max-age=0";
// 重置全部的内部状态
cookie = {};
key = [];
this.length = 0;
};
}
推荐前端学习群:html5/css3/js/jq/nodejs/div 群号:339840649