简单用法:
// 设置url
window.localStorage.setItem('url','http://www.baidu.com');
// 获取url
var url = window.localStorage.getItem('url');
console.log(url); // output http://www.baidu.com
简单封装:
// 声明
var store = (function(root){
var _store = root.localStorage;
return {
// 设置值
set:function(key,val){
val = JSON.stringify(val);
_store.setItem(key,val);
},
// 根据key获取对应值
get:function(key){
var val = _store.getItem(key);
try{
return JSON.parse(val);
}catch(e){
return val;
}
},
// 根据key删除指定值
del:function(key){
_store.removeItem(key);
},
// 清空所有
clear:function(){
_store.clear();
}
}
})(window);
// 调用
store.set('url','http://www.baidu.com');
store.get('url'); // http://www.baidu.com
store.del('url');
store.clear();