使用LocalStorage实现Form表单内容本地存储

  • 判断浏览器是否支持localStorage,并将值存入,推荐setItem方法。
if(!window.localStorage) {
    console.log("浏览器不支持localstorage");
    return false;
 }else{
    var storage=window.localStorage;
    // 查询条件localStorage本地存储
    var cfdaCode = $("#cfdaCode").val();
    var productCode = $("#productCode").val();
    var approvalNumber = $("#approvalNumber").val();
    var status = $("#status").val();
    var productName = $("#productName").val();
    var manufactureName = $("#manufactureName").val();
    storage.setItem("cfdaCode", cfdaCode);
    storage.setItem("productCode", productCode);
    storage.setItem("approvalNumber", approvalNumber);
    storage.setItem("status", status);
    storage.setItem("productName", productName);
    storage.setItem("manufactureName", manufactureName);
}
  • 取出localStorage中的值,使用getItem方法。
// 读取搜索条件localStorage
 if(!window.localStorage){
    console.log("浏览器不支持localstorage");
 }else{
    var storage = window.localStorage;
    var cfdaCode = storage.getItem("cfdaCode");
    var productCode = storage.getItem("productCode");
    var approvalNumber = storage.getItem("approvalNumber");
    var status = storage.getItem("status");
    var productName = storage.getItem("productName");
    var manufactureName = storage.getItem("manufactureName");
    if (cfdaCode != null && cfdaCode != "") {
        $("#cfdaCode").find("option[value='" + cfdaCode + "']").attr("selected",true);
    }
    $("#productCode").val(productCode);
    $("#approvalNumber").val(approvalNumber);
    if (status != null && status != "") {
        $("#status").find("option[value='" + status + "']").attr("selected",true);
    }
    $("#productName").val(productName);
    $("#manufactureName").val(manufactureName);
}
  • 清除localStorage中的值
// 重置-清除localStorage
 $("#reBtn").bind("click",function(){
   if(!window.localStorage){
     console.log("浏览器不支持localstorage");
   }else{
     storage.clear();
   }
   $("#cfdaCode").find("option:first").attr("selected",true);
   $("#productCode").val("");
   $("#approvalNumber").val("");
   $("#status").find("option:first").attr("selected",true);
   $("#productName").val("");
   $("#manufactureName").val("");
 });

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

相关推荐