//本地存储,localStorage类没有存储空间的限制,而cookieStorage有存储大小限制
//在不支持localStorage的情况下会自动切换为cookieStorage
window.myStorage = (new (function () {
var storage; //声明一个变量,用于确定使用哪个本地存储函数
if (window.localStorage) {
storage = localStorage; //当localStorage存在,使用H5方式
}
else {
storage = cookieStorage; //当localStorage不存在,使用兼容方式
}
this.setItem = function (key, value) {
storage.setItem(key, value);
};
this.getItem = function (name) {
return storage.getItem(name);
};
this.removeItem = function (key) {
storage.removeItem(key);
};
this.clear = function () {
storage.clear();
};
})());
//《JavaScript权威指南》一书中有实现基于cookie的存储API,我把代码敲下来
// 另外,书中的代码有错,以下为无BUG版并修改成1000天相当长的存储时间
window.cookieStorage = (new (function () {
var maxage = 60 * 60 * 24 * 1000;
var path = '/';
var cookie = getCookie();
function getCookie() {
var cookie = {};
var all = document.cookie;
if (all === "")
return cookie;
var list = all.split("; ");
for (var i = 0; i < list.length; i++) {
var cookies = list[i];
var p = cookies.indexOf("=");
var name = cookies.substring(0, p);
var value = cookies.substring(p + 1);
value = decodeURIComponent(value);
cookie[name] = value;
}
return cookie;
}
var keys = [];
for (var key in cookie)
keys.push(key);
this.length = keys.length;
this.key = function (n) {
if (n < 0 || n >= keys.length)
return null;
return keys[n];
};
this.setItem = function (key, value) {
if (!(key in cookie)) {
keys.push(key);
this.length++;
}
cookie[key] = value;
var cookies = key + "=" + encodeURIComponent(value);
if (maxage)
cookies += "; max-age=" + maxage;
if (path)
cookies += "; path=" + path;
document.cookie = cookies;
};
this.getItem = function (name) {
return cookie[name] || null;
};
this.removeItem = function (key) {
if (!(key in cookie))
return;
delete cookie[key];
for (var i = 0; i < keys.length; i++) {
if (keys[i] === key) {
keys.splice(i, 1);
break;
}
}
this.length--;
document.cookie = key + "=; max-age=0";
};
this.clear = function () {
for (var i = 0; i < keys.length; i++)
document.cookie = keys[i] + "; max-age=0";
cookie = {};
keys = [];
this.length = 0;
};
})());
调用方法:
(1)localStorage.setItem(键名,键值)
在本地客户端存储一个字符串类型的数据,其中,第一个参数“键名”代表了该数据的标识符,而第二个参数“键值”为该数据本身。如:
localStorage.setItem("coffeeType", "mocha"); //存储键名为coffeeType和键值为mocha的数据到本地
localStorage.setItem("coffeePrice", "28"); //有了上一句做参考,这句意思你该理解了吧
(2)localStorage.getItem(键名)
读取已存储在本地的数据,通过键名作为参数读取出对应键名的数据。如:
var data = localStorage.getItem("coffeeType"); //读取对应键名为coffeeType的数据
(3)localStorage.removeItem(键名)
移除已存储在本地的数据,通过键名作为参数删除对应键名的数据。如:
localStorage.removeItem("coffeeType"); //从本地存储中移除键名为coffeeType的数据
(4)localStorage.clear()
移除本地存储所有数据。如:
localStorage.clear(); //保存着的"coffeePrice/28"键/值对也被移除了,所有本地数据拜拜
(5)另外,sessionStorage中的四个函数与以上localStorage类的函数用法基本一致,就不再详解。