<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数据管理</title>
</head>
<body>
<script>
/*
* 本地存储类
* 参数 preId 本地储存数据前缀
* 参数 timeSgin 时间戳与数据存储之间的拼接符
* */
var BaselocalStorage = function(preId,timeSgin){
//定义本地存储库的前缀
this.preId = preId;
//定义时间戳与数据存储之间的拼接符
this.timeSgin = timeSgin || '|-|';
}
//本地存储类的原型方法
BaselocalStorage.prototype = {
//操作状态
status:{
success:0,
fail:1,
over:2,
time:3
},
//保存本地储存连接
storage:localStorage ||window.localStorage,
//获取本地储存数据库真实字段
getKey:function (key) {
return this.preId+key;
},
//添加修改
/**
* 添加(修改)数据
* 参数 key 数据字段标识
* 参数 value 数据值
* 参数 callback 回调函数
* 参数 time 添加时间
* */
set:function (key,value,callback,time) {
//默认状态成功时
var status = this.status.success,
//获取真实字段
key = this.getKey(key);
try{
//参数时间参数获取时间段时间戳
time = new Data(time).getTime()||time.getTime();
}catch (e) {
time = new Date().getTime() + 1000*60*60*24*31;
}
try{
//向数据库中添加数据
this.storage.setItem(key,time + this.timeSgin + value);
}catch (e) {
status = this.status.over;
}
callback && callback.call(this,status,key,value);
},
/**
* 获取数据
* 参数 key 数据段标识符
* 参数 callback 回调函数
* **/
get:function (key,callback) {
//设置默认状态
console.log("hello");
var status = this.status.success,
key = this.getKey(key),
//默认值为空
value =null,
//时间戳与存储数据之间的拼接字
timeSigin = this.timeSgin.length,
//缓存当前对象
that = this,
//时间戳
index,
//最终结果
result;
try{
//获取字段对应的数据字符串
value = that.storage.getItem(key);
}catch (e) {
//获取失败返回失败状态,数据结果为null
result = {
status:that.status.fail,
value:null
}
//执行回调
callback&&callback.call(this,result,status,result.value);
return result;
}
if (value){
//获取时间戳与数据之间的拼接起始位置
index = value.indexOf(that.timeSgin);
//获取时间戳
time = +value.slice(0,index);
//如果时间按为过期
if(new Date(time).getTime()>new Date().getTime()||time ==0){
//获取数据结果
value = value.split(index+time);
}else{
status = that.status.fail;
}
//设置结果
result ={
status:status,
value:value
};
callback&&callback.call(this,result.status,result.value);
//返回结果
return result;
}else {
console.log("不存在该字段");
return null;
}
},
//删除数据
remove:function (key,callback) {
//设置默认操作状态为失败
var status = this.status.fail,
key = this.getKey(key),
//设置为默认数据结果为空
value = null;
try{
//获取字段对应的数据
value = this.storage.getItem(key);
}catch (e) {
}
if (value){
//如果数据存在
try{
//删除数据
this.storage.removeItem(key);
//设置操作成功
status = this.status.success;
}catch (e) {
//设置操作失败
status = this.status.fail;
}
}
//执行回调函数
callback && callback.call(this,status,status>0?null:value.slice(value.indexOf(this.timeSgin)+this.timeSgin.length))
}
}
var Ls = new BaselocalStorage('Ls__');
Ls.set('a','yqf',function (status,key,value) {
if (status==0)
console.log("信息添加成功 "+key+"/"+value);
});
console.log("hello");
Ls.get('a',function (status) {
console.log(status);
});
Ls.remove('a',function () {
console.log(arguments);
});
Ls.get('a',function () {
console.log(arguments);
});
</script>
</body>
</html>