本地存储localstorage

  一、本地存储localstorage

     主要应用于离线存储、本地数据统计上报。localstorage可以在本地存储5M的数据,可以很好的满足这两

种需求。同时可以保存一些长久不变的信息,不需要网络请求加载。
     

二、浏览器支持情况

基本上除IE6-7不支持外,其他浏览器都是支持。
测试浏览器兼容方法:
if(window.localStorage){  
     // do loacalstorage   
} else {  
     // 浏览器不支持  
}  


三、通用接口实现
1、数据库操作接口
/* 处理所有的表单数据 */
window.db = {
	/* 获取所有数据 */
	_getAll : function(){
		var returnDta = {};
		for(table in this._db()){
			var tableDb = JSON.stringify(localStorage.getItem(table));
			returnDta[table] = tableDb;
		}
		return returnDta;
	},

	/* 清除所有表单数据 */
	_clear : function(){
		for(table in this._db){
			localStorage.removeItem(table);
		}
		localStorage.removeItem("dbName");
	},

	/* 获取已经有的表单对象 */
	_getInstanceTable : function(tableName){
		if(this._db[tableName]){
			return new tdb(tableName);
		}
		return false;
	},

	_getDb : JSON.parse(localStorage.getItem('dbName'))

}

2、表单操作接口
  1. /* 处理table表单的数据 */  
    function tdb(tableName){  
      
         /* 存储当前的数据库的tableName */  
         this._tableName = tableName;  
         /* 添加新的table数据表单 */  
         this.addTable = function(){  
              var db = JSON.parse(localStorage.getItem('dbName'));  
              if(!db){  
                   db = {};  
              } else if(db[tableName]){  
                   return true;  
              }   
              db[tableName] = tableName;  
              localStorage.setItem("dbName", JSON.stringify(db));  
              return db;  
         }();  
      
         /* 删除不需要的table表单 */  
         this.removeTable = function(){  
              localStorage.removeItem(this._tableName);  
         };  
      
         /* 获取表单中的数据值 */  
         this._get = function(key){  
              var dbData =  this._getTableData();  
              return dbData[key];  
         }  
      
         /* 向表单插入数据 */  
         this._insert = function(key, value){  
              var currentData = this._getTableData();  
              currentData[key] = value;  
              localStorage.setItem(this._tableName, JSON.stringify(currentData));  
         }  
      
         /* 获取表单的所有数据 */  
         this._getTableData = function(){  
              var db = JSON.parse(localStorage.getItem(this._tableName));  
              if(db){  
                   return db;  
              }  
              return {};  
         }  
    }  




四、使用方法

例子:在本地建立如下数据库
有三个表单
t_total、t_click_time
t_total插入字段t_user、t_number
t_clickTime插入字段t_click_times、t_time

代码如下:
var totalDb = new tdb("t_total");  
totalDb._insert("t_user","danhuang");  
totalDb._insert("t_number","600");  
  
var tctDb   = new tdb("t_click_time");  
tctDb._insert("t_click_times","50");  
tctDb._insert("t_time","2012-09-05");  

最后我们查看本地数据:



发布了81 篇原创文章 · 获赞 270 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/danhuang2012/article/details/7945356