主頁 > 知識庫 > 詳解HTML5 LocalStorage 本地存儲

詳解HTML5 LocalStorage 本地存儲

熱門標簽:中紳電銷智能機器人 農(nóng)村住宅地圖標注 鶴壁手機自動外呼系統(tǒng)怎么安裝 濟南辦理400電話 鄭州電銷外呼系統(tǒng)違法嗎 ai電銷機器人連接網(wǎng)關(guān) 跟電銷機器人做同事 威海營銷外呼系統(tǒng)招商 漳州人工外呼系統(tǒng)排名

1.前言

HTML5 storage提供了一種方式讓網(wǎng)站能夠把信息存儲到你本地的計算機上,并再以后需要的時候進行獲取。這個概念和cookie相似,區(qū)別是它是為了更大容量存儲設(shè)計的。Cookie的大小是受限的,并且每次你請求一個新的頁面的時候cookie都會被發(fā)送過去。HTML5的storage是存儲在你的計算機上,網(wǎng)站在頁面加載完畢后可以通過Javascript來獲取這些數(shù)據(jù)。首先自然是檢測瀏覽器是否支持本地存儲。在HTML5中,本地存儲是一個window的屬性,包括localStorage和sessionStorage,從名字應(yīng)該可以很清楚的辨認二者的區(qū)別,前者是一直存在本地的,后者只是伴隨著session,窗口一旦關(guān)閉就沒了。二者用法完全相同,這里以localStorage為例。

if(window.localStorage){
 alert('支持localStorage');
}else{
 alert('不支持localStorage');
}

2.基本用法

存儲數(shù)據(jù)的方法就是直接給window.localStorage添加一個屬性,例如:window.localStorage.a 或者 window.localStorage["a"]。它的讀取、寫、刪除操作方法很簡單,是以鍵值對的方式存在的,如下:

localStorage.name = "kobi";//設(shè)置name為"kobi"
localStorage["name"] = "koko";//設(shè)置name為"koko",覆蓋上面的值
localStorage.setItem("age","18");//設(shè)置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)獲得相應(yīng)的鍵,再用getItem()方法獲得對應(yīng)的值
  document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>");
 }
}

 3.業(yè)務(wù)需求

表單實時保存數(shù)據(jù),下次打開則提示是否繼續(xù)編輯。圖片等控件不支持,只支持簡單的控件?!痉乐雇蝗粩嚯娀驗g覽器崩潰時,下次打開還可以繼續(xù)編輯并保存】。這樣自然而然就想到了HTML5的本地存儲功能。既然js寫的爛,寫的差,就當練手了。

其實這些數(shù)據(jù)的保存很簡單,無非就是一些簡單的標簽數(shù)據(jù)的保存。先來一個最簡單的js版本。

/**
 * 功能:保存用戶修改完form標簽內(nèi)容在LocalStorage中。
 * 作者:黃金鋒 
 * 版本:version 2.0
 */

define(function () {

    //從localStorage中加載數(shù)據(jù)
    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);
                });
            }
        });

        //保存修改的數(shù)據(jù)
        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中的數(shù)據(jù)
    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控件的數(shù)據(jù)保存

Grid控件其實就是一個div,公司的一些頁面表單都是動態(tài)生成的,表單上面的控件也是動態(tài)生成的,所有很多東西都是自己手寫的。下面是Grid控件的結(jié)構(gòu)。

 <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;">
     申報材料內(nèi)容
    </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數(shù)據(jù)保存的js.

/**
 * 功能:保存用戶修改完form標簽內(nèi)容在LocalStorage中。
 * 作者:黃金鋒 (549387177@qq.com)
 * 日期:2015-11-1  11:14:01
 * 修改:2015-11-19 16:09:00
 * 版本:version 3.0
 */

define(function () {

    //從localStorage中加載數(shù)據(jù)
    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("是否加載緩存數(shù)據(jù)")) {

                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緩存數(shù)據(jù)"))
            {
                //給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);
                });
            }
        });

        //保存修改的數(shù)據(jù)
        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中的數(shù)據(jù)
    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
    }
});

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

標簽:咸陽 甘南 紅河 文山 惠州 營口 蘇州 萍鄉(xiāng)

巨人網(wǎng)絡(luò)通訊聲明:本文標題《詳解HTML5 LocalStorage 本地存儲》,本文關(guān)鍵詞  詳解,HTML5,LocalStorage,本地,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《詳解HTML5 LocalStorage 本地存儲》相關(guān)的同類信息!
  • 本頁收集關(guān)于詳解HTML5 LocalStorage 本地存儲的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章