详解HTML5 LocalStorage 当地储存

日期:2021-02-27 类型:科技新闻 

关键词:上线了小程序官网,年会抽奖小程序免费,做小程序,小程序网站,跑腿小程序

1.序言

HTML5 storage出示了1种方法让网站可以把信息内容储存到你当地的测算机上,并再之后必须的情况下开展获得。这个定义和cookie类似,差别是它是以便更大容量储存设计方案的。Cookie的尺寸是受到限制的,而且每次你恳求1个新的网页页面的情况下cookie都会被推送以往。HTML5的storage是储存在你的测算机上,网站在网页页面载入结束后能够根据Javascript来获得这些数据信息。最先当然是检验访问器是不是适用当地储存。在HTML5中,当地储存是1个window的特性,包含localStorage和sessionStorage,从姓名应当能够很清晰的分辨2者的差别,前者是1直存在当地的,后者只是随着着session,对话框1旦关掉就没了。2者用法彻底同样,这里以localStorage为例。

if(window.localStorage){
 alert('适用localStorage');
}else{
 alert('不适用localStorage');
}

2.基础用法

储存数据信息的方式便是立即给window.localStorage加上1个特性,比如: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()。假如期待1次性消除全部的键值对,可使用clear()。此外,HTML5还出示了1个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写的烂,写的差,就当练手了。

实际上这些数据信息的储存很简易,不过便是1些简易的标识数据信息的储存。先来1个最简易的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控制实际上便是1个div,企业的1些网页页面表单全是动态性转化成的,表单上面的控制也是动态性转化成的,全部许多物品全是自身笔写的。下面是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)
 * 时间:2015⑴1⑴  11:14:01
 * 改动:2015⑴1⑴9 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
    }
});

以上便是本文的所有內容,期待对大伙儿的学习培训有一定的协助,也期待大伙儿多多适用脚本制作之家。