详解HTML5LocalStorage本地存储

建站知识 admin
本篇文章主要介绍了HTML5 LocalStorage 本地存储 ,HTML5 storage提供了一种方式让网站能够把信息存储到你本地的计算机上,并再以后需要的时候进行获取。有兴趣的可以了解一下。

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="{&quot;ID&quot;:&quot;$[ID]&quot;,&quot;IID&quot;:&quot;$(autoid)&quot;}" /> 
   <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
    }
});

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

转载请注明: 百歌建站 » 详解HTML5LocalStorage本地存储