详解HTML5 LocalStorage 本地存储
1.前言
html5 storage提供了一种方式让网站能够把信息存储到你本地的计算机上,并再以后需要的时候进行获取。这个概念和cookie相似,区别是它是为了更大容量存储设计的。cookie的大小是受限的,并且每次你请求一个新的页面的时候cookie都会被发送过去。html5的storage是存储在你的计算机上,网站在页面加载完毕后可以通过javascript来获取这些数据。首先自然是检测浏览器是否支持本地存储。在html5中,本地存储是一个window的属性,包括localstorage和sessionstorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了。二者用法完全相同,这里以localstorage为例。
if(window.localstorage){ alert('支持localstorage'); }else{ alert('不支持localstorage'); }
2.基本用法
存储数据的方法就是直接给window.localstorage添加一个属性,例如:window.localstorage.a 或者 window.localstorage["a"]。它的读取、写、删除操作方法很简单,是以键值对的方式存在的,如下:
localstorage.name = "kobi";//设置name为"kobi" localstorage["name"] = "koko";//设置name为"koko",覆盖上面的值 localstorage.setitem("age","18");//设置age为"18" var a1 = localstorage["name"];//获取name的值 var a2 = localstorage.age;//获取age的值 var b = localstorage.getitem("name");//获取name的值 localstorage.removeitem("c");//清除c的值
这里最推荐使用的自然是getitem()和setitem(),清除键值对使用removeitem()。如果希望一次性清除所有的键值对,可以使用clear()。另外,html5还提供了一个key()方法,可以在不知道有哪些键值的时候使用,如下:
var storage = window.localstorage; function showstorage(){ for(var i=0;i<storage.length;i++){ //key(i)获得相应的键,再用getitem()方法获得对应的值 document.write(storage.key(i)+ " : " + storage.getitem(storage.key(i)) + "<br>"); } }
3.业务需求
表单实时保存数据,下次打开则提示是否继续编辑。图片等控件不支持,只支持简单的控件。【防止突然断电或浏览器崩溃时,下次打开还可以继续编辑并保存】。这样自然而然就想到了html5的本地存储功能。既然js写的烂,写的差,就当练手了。
其实这些数据的保存很简单,无非就是一些简单的标签数据的保存。先来一个最简单的js版本。
/** * 功能:保存用户修改完form标签内容在localstorage中。 * 作者:黄金锋 * 版本:version 2.0 */ define(function () { //从localstorage中加载数据 function onload(form) { var fh = form_handler; var p = fh.getparams(form); if (!p.bimid || !p.formid || !p.iid) { return; } var id = 'form_' + dci.loginuser.userid + '_' + p.bimid + '_' + p.formid + '_' + p.iid; //alert(id); var formdatadb; var allcontrol = $(form).find("input:text[name],textarea[name]"); //从本地取 var storage = localstorage.getitem(id); if (storage != null) { var mydata = json.parse(storage); allcontrol.each(function (i, e) { var name = $(e).attr("name"); if (mydata[name] != null) { $(e).val(mydata[name]); $(e).change(); } }); } //绑定change事件 allcontrol.each(function (i, el) { var name = $(el).attr('name'); if (name) { $(el).on('change', function () { onchange(this); }); } }); //保存修改的数据 function onchange(el) { var storage = localstorage.getitem(id); if (storage == null) { formdatadb = new object(); var key = $(el).attr("name"); var value = $(el).val(); formdatadb[key] = value; localstorage.setitem(id, json.stringify(formdatadb)); } else { var mydata = json.parse(storage); var key = $(el).attr("name"); var value = $(el).val(); mydata[key] = value; localstorage.setitem(id, json.stringify(mydata)); } } }; //删除localstorage中的数据 function onsave(form) { var fh = form_handler; var p = fh.getparams(form); var id = 'form_' + dci.loginuser.userid + '_' + p.bimid + '_' + p.formid + '_' + p.iid; localstorage.removeitem(id); var allgrid = $(form).find(".form-table"); var formid = $(form).data("formid"); allgrid.each(function (index,element) { var formname = $(element).find("input:hidden[data-formid]").attr("name"); var storagekey = "form_" + formid + "_" + formname; localstorage.removeitem(storagekey); }); } return { onload: onload, onsave: onsave, } });
表单都是自动通过模版生成的,这里附上表单加载需要的form.js.
代码太长,这里就不直接贴出来了,大家自己下载下来看吧
4.grid控件的数据保存
grid控件其实就是一个div,公司的一些页面表单都是动态生成的,表单上面的控件也是动态生成的,所有很多东西都是自己手写的。下面是grid控件的结构。
<div class="fm000103-sbclbj form-table "> <input data-datagrid="true" data-formid="fm000034" name="sbclbj" type="hidden" /> <input data-param="init" type="hidden" value="{"id":"$[id]","iid":"$(autoid)"}" /> <input data-param="initsame" type="hidden" value="[]" /> <div class="form-table-header"> <div style="width:48px;"> 编辑 </div> <div style="width:50px;"> 序号 </div> <div style="width:60px;"> 是否上传 </div> <div style="width:380px;"> 申报材料内容 </div> <div style="width:80px;"> 备注 </div> </div> <div class="form-table-body"> <table class="table-hover"> <colgroup span="6"> <col width="48" /> <col width="50" data-type="rownumber" /> <col width="0" data-type="label" data-index="id" class="hidden" /> <col width="0" data-type="label" data-index="iid" class="hidden" /> <col width="60" data-type="checkbox" data-index="cdzl" /> <col width="380" data-type="textarea" data-index="atdesc" /> <col width="80" data-type="textarea" data-index="bz" /> </colgroup> <tbody> <tr> <td class="form-table-edit"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></td> <td>1</td> <td class="hidden">bm00001141</td> <td class="hidden">4643</td> <td><input type="checkbox" value="1" checked="checked" /></td> <td>11111</td> <td>2222</td> </tr> <tr> <td class="form-table-edit"><span class="glyphicon glyphicon-edit" aria-hidden="true"></span></td> <td>2</td> <td class="hidden">bm00001141</td> <td class="hidden">4644</td> <td><input type="checkbox" value="0" /></td> <td>87789789789798789</td> <td>333</td> </tr> </tbody> </table> </div> <div class="form-table-footer"> <button type="button" class="btn add-row">新增</button> <button type="button" class="btn del-row">删除</button> </div> </div>
下面是完成grid数据保存的js.
/** * 功能:保存用户修改完form标签内容在localstorage中。 * 作者:黄金锋 (549387177@qq.com) * 日期:2015-11-1 11:14:01 * 修改:2015-11-19 16:09:00 * 版本:version 3.0 */ define(function () { //从localstorage中加载数据 function onload(form) { var fh = form_handler; var p = fh.getparams(form); if (!p.bimid || !p.formid || !p.iid) { return; } var id = 'form_' + dci.loginuser.userid + '_' + p.bimid + '_' + p.formid + '_' + p.iid; var formdatadb; var allcontrol = $(form).find("input:text[name],textarea[name]"); //从本地取 var storage = localstorage.getitem(id); if (storage != null) { if (confirm("是否加载缓存数据")) { var mydata = json.parse(storage); allcontrol.each(function (i, e) { var name = $(e).attr("name"); if (mydata[name] != null) { $(e).val(mydata[name]); $(e).change(); } }); } } var allgrid = $(form).find(".form-table"); var formid = $(form).data("formid"); var formstorage= localstorage.getitem("form_" + formid + "_isgriddata"); if (formstorage=="1") { if (confirm("是否加载grid缓存数据")) { //给grid控件赋值 allgrid.each(function (index, element) { var formname = $(element).find("input:hidden[data-formid]").attr("name"); var ipt = $(element).find("input[name]"); var table = $(element).find("input:hidden[data-formid]").siblings(".form-table-body").find(".table-hover"); var storagekey = "form_" + formid + "_" + formname; var data = localstorage.getitem(storagekey); var mydata = json.parse(data); if (mydata != null) { alert(data); var inserttotal = mydata["total"]["inserttotal"]; var deltotal = mydata["total"]["deltotal"]; var updatetotal = mydata["total"]["updatetotal"]; var triidindex = mydata["triidindex"]["iid"]; if (inserttotal > 0) { for (var i = 0; i < inserttotal; i++) { var tr = $('<tr></tr>'); var row_data = mydata["insert"][i]; table.find('colgroup col').each(function (idx, el) { var td = $('<td></td>'); if (idx == 0) { td.append('<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>'); td.addclass('form-table-edit'); } else { var index = $(el).data('index'); var type = $(el).data('type') if (type == "rownumber") { var val = row_data["rownumber"]; td.html(val); } if (type == "checkbox") { var val = row_data[index]; td.append('<input type="checkbox" value="' + val + '" ' + (val == '1' ? 'checked="checked"' : '') + ' />'); } if (index && type != "checkbox") { td.html(row_data[index]); } } if ($(el).attr('width') == '0') td.addclass('hidden'); td.appendto(tr); }); //table.find("tbody").append(tr); table.append(tr); tr.data("insert", true); ipt.change(); } } if (updatetotal > 0) { for (var i = 0; i < updatetotal; i++) { var row_data = mydata["update"][i]; var triid = row_data["triid"]; var trindex; table.find("tr").each(function (idx, ele) { var iid = $(ele).find("td").eq(triidindex).html(); if (iid == triid) { trindex = idx; } }); var cells = table.find("tr").eq(trindex); table.find('colgroup col').each(function (idx, el) { var index = $(el).data('index'); if (index) { var td = cells.find("td").eq(idx); var type = $(el).data('type'); var test =new object(); var text = row_data[index]; if (type == 'checkbox') { var ck = td.find('input[type="checkbox"]'); if (text == '1') ck.prop('checked', true); else ck.prop('checked', false); } else { td.text(text); } } }); cells.data("update", true); ipt.change(); } } if (deltotal > 0) { for (var i = 0; i < deltotal; i++) { var row_data = mydata["del"][i]; var triid = row_data["triid"]; table.find("tr").each(function (idx,ele) { var iid = $(ele).find("td").eq(triidindex).html(); if ( iid== triid) { $(this).css("display", "none"); $(this).data("delete", true); ipt.change(); } }); } } } }); } } //绑定change事件 allcontrol.each(function (i, el) { var name = $(el).attr('name'); if (name) { $(el).on('change', function () { onchange(this); }); } }); //保存修改的数据 function onchange(el) { var storage = localstorage.getitem(id); if (storage == null) { formdatadb = new object(); var key = $(el).attr("name"); var value = $(el).val(); formdatadb[key] = value; localstorage.setitem(id, json.stringify(formdatadb)); } else { var mydata = json.parse(storage); var key = $(el).attr("name"); var value = $(el).val(); mydata[key] = value; localstorage.setitem(id, json.stringify(mydata)); } } }; //删除localstorage中的数据 function onsave(form) { var fh = form_handler; var p = fh.getparams(form); var id = 'form_' + dci.loginuser.userid + '_' + p.bimid + '_' + p.formid + '_' + p.iid; localstorage.removeitem(id); var allgrid = $(form).find(".form-table"); var formid = $(form).data("formid"); allgrid.each(function (index,element) { var formname = $(element).find("input:hidden[data-formid]").attr("name"); var storagekey = "form_" + formid + "_" + formname; localstorage.removeitem(storagekey); }); localstorage.setitem("form_" + formid + "_isgriddata", null); } function ongridadd(form, table, data, tr) { var inputflag = table.closest("div .form-table").find("input:hidden[data-formid]") var storagekey; var formid = $(form).data("formid");; localstorage.setitem("form_" + formid + "_isgriddata", "1"); var rownumber = table.find(".active").children().eq(1).html(); var triidindex; var triid; table.find("col").each(function (idx, ele) { if ($(ele).data("index") == "iid") { triid = table.find(".active").children().eq(idx).html(); triidindex = idx; } }); var insertobj = { triid: triid, rownumber: rownumber }; var columnarr = table.children().find("[data-index]"); if (columnarr) { columnarr.each(function (index, element) { var flag = $(element).data("index"); insertobj[flag] = data[flag]; }); } if (inputflag && triid) { storagekey = "form_" + formid + "_" + inputflag.attr("name"); //var mydata = "{'insert':[{'triid':'1','id':'test','iid':'测试'},{'triid':'2','id':'test2','iid':'测试2'}],'update':[{'triid':'3','id':'test3','iid':'测试3'},{'triid':'4','id':'test4','iid':'测试4'}],'del':[{'triid':'1'},{'triid':'2'}]}"; var getlocalstorage = localstorage.getitem(storagekey); if (getlocalstorage) { var dataobj = json.parse(getlocalstorage); var inserttotal = dataobj["total"]["inserttotal"]; dataobj["insert"][inserttotal] = insertobj; dataobj["total"]["inserttotal"] = inserttotal + 1; localstorage.setitem(storagekey, json.stringify(dataobj)); } else { var mydata = { total: { inserttotal: 1, updatetotal: 0, deltotal: 0 }, insert: [insertobj], update: [], del: [], notes: { storagekey: storagekey }, triidindex: { iid: triidindex } }; localstorage.setitem(storagekey, json.stringify(mydata)); } } } function ongridedit(form, table, data, tr) { var inputflag = table.closest("div .form-table").find("input:hidden[data-formid]") var formid = $(form).data("formid"); var storagekey = "form_" + formid + "_" + inputflag.attr("name"); localstorage.setitem("form_" + formid + "_isgriddata", "1"); var mysourcedata = {}; var triidindex; table.find("col").each(function (idx, ele) { var index = $(ele).data("index"); var type = $(ele).data("type"); if (index) { if (type == "checkbox") { var val = table.find(".active").children().eq(idx).html(); var value =$(val).val(); mysourcedata[index] = value; } else { if (index == "iid") { triidindex = idx; } mysourcedata[index] = table.find(".active").children().eq(idx).html(); } } }); var triid = mysourcedata["iid"]; var updateobj = { triid: triid }; $.extend(updateobj, mysourcedata); var getlocalstorage = localstorage.getitem(storagekey); if (getlocalstorage) { var dataobj = json.parse(getlocalstorage); var inserttotal = dataobj["total"]["inserttotal"]; var updatetotal = dataobj["total"]["updatetotal"]; if (inserttotal > 0)//新增后在编辑 { for (var i = 0; i < inserttotal; i++) { var row_data = dataobj["insert"][i]; if (row_data["triid"] == triid) { $.extend(dataobj["insert"][i], updateobj); } } } if (updatetotal > 0)//编辑之后在编辑 { for (var i = 0; i < updatetotal; i++) { var row_data = dataobj["update"][i]; if (row_data["triid"] == triid) { $.extend(dataobj["update"][i], updateobj); } } } var updatetotal = dataobj["total"]["updatetotal"]; dataobj["update"][updatetotal] = updateobj; dataobj["total"]["updatetotal"] = updatetotal + 1; localstorage.setitem(storagekey, json.stringify(dataobj)); } else { var mydata = { total: { inserttotal: 0, updatetotal: 1, deltotal: 0 }, insert: [], update: [updateobj], del: [], notes: { storagekey: storagekey }, triidindex: { iid: triidindex } }; localstorage.setitem(storagekey, json.stringify(mydata)); } var testdata = localstorage.getitem(storagekey); var mydata = json.parse(testdata); if (testdata != null) { alert(testdata); //alert(mydata); //alert(mydata["total"]["inserttotal"]); //alert(mydata["insert"][0]["id"]); } } function ongriddel(form, table, tr) { var inputflag = table.closest("div .form-table").find("input:hidden[data-formid]") var formid = $(form).data("formid"); var storagekey = "form_" + formid + "_" + inputflag.attr("name");; localstorage.setitem("form_" + formid + "_isgriddata", "1"); var triidindex; var triid; table.find("col").each(function (idx, ele) { if ($(ele).data("index") == "iid") { triidindex = idx; triid = tr.find("td").eq(idx).html(); } }); var delobj = { triid: triid }; var getlocalstorage = localstorage.getitem(storagekey); if (getlocalstorage) { var dataobj = json.parse(getlocalstorage); var isinsertdata = false; var isupdatedel = false; var inserttotal = dataobj["total"]["inserttotal"]; var deltotal = dataobj["total"]["deltotal"]; var updatetotal = dataobj["total"]["updatetotal"]; if (inserttotal > 0) { for (var i = 0; i < inserttotal; i++) { var row_data = dataobj["insert"][i]; if (row_data["triid"] == triid) { isinsertdata = true; dataobj["insert"][i] = null; } } } if (updatetotal>0) { for (var i = 0; i < updatetotal; i++) { var row_data = dataobj["update"][i]; if (row_data["triid"] == triid) { isupdatedel = true; dataobj["update"][i] = null; } } } if (isinsertdata) { var temparr = []; for (var i = 0; i < inserttotal; i++) { if (dataobj["insert"][i] != null) { temparr[i]=dataobj["insert"][i]; } } dataobj["insert"] = temparr; dataobj["total"]["inserttotal"] = inserttotal - 1; } else { if (isupdatedel) { var temparr = []; for (var i = 0; i < inserttotal; i++) { if (dataobj["update"][i] != null) { temparr[i] = dataobj["update"][i]; } } dataobj["update"] = temparr; dataobj["total"]["updatetotal"] = updatetotal - 1; } dataobj["del"][deltotal] = delobj; dataobj["total"]["deltotal"] = deltotal + 1; } localstorage.setitem(storagekey, json.stringify(dataobj)); if (dataobj["total"]["inserttotal"] == 0 && dataobj["total"]["updatetotal"] == 0 && dataobj["total"]["deltotal"] == 0) { localstorage.setitem("form_" + formid + "_isgriddata", null); } } else { var mydata = { total: { inserttotal: 0, updatetotal: 0, deltotal: 1 }, insert: [], update: [], del: [delobj], notes: { storagekey: storagekey }, triidindex: { iid: triidindex } }; localstorage.setitem(storagekey, json.stringify(mydata)); } } return { onload: onload, onsave: onsave, ongridadd: ongridadd, ongridedit: ongridedit, ongriddel: ongriddel } });
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: HTML5应用之文件上传
推荐阅读
-
JS实现本地存储信息的方法(基于localStorage与userData)
-
HTMl5的存储方式sessionStorage和localStorage详解
-
HTML5本地存储localStorage、sessionStorage基本用法、遍历操作、异常处理等
-
html5本地存储之localstorage 、本地数据库、sessionStorage简单使用示例
-
html5 localStorage本地存储_动力节点Java学院整理
-
html5本地存储_动力节点Java学院整理
-
HTML5 本地存储实现购物车功能
-
Android本地存储SharedPreferences详解
-
html5中localStorage本地存储的简单使用
-
html5的localstorage详解