使用LocalStorage實現Form表單內容本地儲存

浪味仙人發表於2018-06-01
  • 判斷瀏覽器是否支援localStorage,並將值存入,推薦setItem方法。
 1 if(!window.localStorage) {
 2    console.log("瀏覽器不支援localstorage");
 3    return false;
 4 }else{
 5    var storage=window.localStorage;
 6    // 查詢條件localStorage本地儲存
 7    var cfdaCode = $("#cfdaCode").val();
 8    var productCode = $("#productCode").val();
 9    var approvalNumber = $("#approvalNumber").val();
10    var status = $("#status").val();
11    var productName = $("#productName").val();
12    var manufactureName = $("#manufactureName").val();
13    storage.setItem("cfdaCode", cfdaCode);
14    storage.setItem("productCode", productCode);
15    storage.setItem("approvalNumber", approvalNumber);
16    storage.setItem("status", status);
17    storage.setItem("productName", productName);
18    storage.setItem("manufactureName", manufactureName);
19 }        
  • 取出localStorage中的值,使用getItem方法。
 1 // 讀取搜尋條件localStorage
 2 if(!window.localStorage){
 3    console.log("瀏覽器不支援localstorage");
 4 }else{
 5    var storage = window.localStorage;
 6    var cfdaCode = storage.getItem("cfdaCode");
 7    var productCode = storage.getItem("productCode");
 8    var approvalNumber = storage.getItem("approvalNumber");
 9    var status = storage.getItem("status");
10    var productName = storage.getItem("productName");
11    var manufactureName = storage.getItem("manufactureName");
12    if (cfdaCode != null && cfdaCode != "") {
13        $("#cfdaCode").find("option[value=`" + cfdaCode + "`]").attr("selected",true);
14    }
15    $("#productCode").val(productCode);
16    $("#approvalNumber").val(approvalNumber);
17    if (status != null && status != "") {
18        $("#status").find("option[value=`" + status + "`]").attr("selected",true);
19    }
20    $("#productName").val(productName);
21    $("#manufactureName").val(manufactureName);
22 } 
  • 清除localStorage中的值
 1 // 重置-清除localStorage
 2 $("#reBtn").bind("click",function(){
 3   if(!window.localStorage){
 4     console.log("瀏覽器不支援localstorage");
 5   }else{
 6     storage.clear();
 7   }
 8   $("#cfdaCode").find("option:first").attr("selected",true);
 9   $("#productCode").val("");
10   $("#approvalNumber").val("");
11   $("#status").find("option:first").attr("selected",true);
12   $("#productName").val("");
13   $("#manufactureName").val("");
14 });

 參考:https://www.cnblogs.com/st-leslie/p/5617130.html

 

相關文章