Home  >  Article  >  Web Front-end  >  web基于浏览器的本地存储方法应用_javascript技巧

web基于浏览器的本地存储方法应用_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:47:531119browse

在客户端存储数据时,我们一般都用cookie(不敏感数据),但是在客户端越来越富的今天,cookie可存储的量(每个域最大4k)实在是小。
在HTML5中有localStorage可使用,但是这就抛弃了IE8-。为了兼容,我们可以翻出IE很久以前就搞的一个存储方法:
给一个元素添加一个特殊的样式url(#default#userData),之后就可以通过setAttribute和getAttribute来存取键值对形式的数据了。
要注意的一点就是在数据改变后要使用save方法,而数据加载初期要load。
接下来就贴上使用方法,当使用的浏览器支持HTML5时,就使用localStorage。

复制代码 代码如下:

var localStorage = (function(db) {
if (typeof db.clear == "function") {
return db;
}
var database = document.createElement("div")
database.id = "database";
database.style.behavior = "url(#default#userData)";
document.body.appendChild(database);
database.load("DataStore");
return {
setItem: function(key, val) {
database.setAttribute(key, val);
database.save("DataStore");
}
, getItem: function(key) {
return database.getAttribute(key);
}
, removeItem: function(key) {
database.removeAttribute(key);
database.save("DataStore");
}
};
} (localStorage || {}));

不过就算兼容了 还是会有问题存在,例如在IE上存储的信息,通过Chrome打开时就获取不到了。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn