LocalStorage:重新加载页面时不显示行表

时间:2017-12-15 23:37:19

标签: javascript jquery

早上好。

我已将表存储到localStorage。

但是当我重新加载页面时,默认表中的不显示。

如果我禁用初始化,它将正常工作,

但不是当我添加新表时,重新加载页面时不会显示默认表:

// Defaul Table 
$("#mainTable").dataTable({
            "ajax": "https://api.myjson.com/bins/1hes6z",
            "columns": [{
                "data": "id"
            }, {
                "data": "name"
            }, {
                "data": "subtype"
            }, {
                "data": "approximate_count"
            }, {
                "data": "time_created"
            }],
        });

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = '<div class="tab-pane" id="folder' + localStorage.Index + '">' +
      '<div class="zf-table">' +
      '<table id="table' + localStorage.Index + '" class="table table-bordered table-hover myFade dynamicTable">' +
      '<thead>' +
      '<tr>' +
      '<th style="border-color:rgb(221, 221, 221);">&nbsp;</th>' +
      '<th>Audience Name</th>' +
      '<th>Type</th>' +
      '<th>Size</th>' +
      '<th>Date Created</th>' +
      '<th>Action</th>' +
      '</tr>' +
      '</thead><tbody></tbody>' +
      '</table>' +
      '</div>' +
      '</div>';
    return addTable;
  }

  if (true) {
    /** INDEX FOR INCREMENT ID **/
    if (typeof(Storage) !== "undefined") {
      if (localStorage.Index) {
        localStorage.Index = Number(localStorage.Index) + 1;
      } else {
        localStorage.Index = 1;
      }
    } // if storage

    var resultTable = JSON.parse(localStorage.getItem("tableList"));
    if (resultTable == null) {
      resultTable = [];
    }
    let newtableHTML = getTableList();
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultFolder array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

    /* append Table baru */
    $('.tab-content').append(newtableHTML);
    var newTable = $("#table" + localStorage.Index).dataTable();
    alert("sucess create table");

  } else {
    alert("Failed create Table");
  }
}); // submitButton func


//on init fill the table-content
$(document).ready(function() { 

$("#mainTable").dataTable();

var resultTable = JSON.parse(localStorage.getItem("tableList"));
if (resultTable != null) {
  //get the nav reference in DOM
  let tableContent = $(".tab-content");

  //clear the html contents
  tableContent.html('');

  for (var i = 0; i < resultTable.length; i++) {
    var items = resultTable[i];
    $(".tab-content").append(items.table);
  }
  $(".dynamicTable").dataTable();
} else {
 let inititalTable = [];
  inititalTable.push({
    table: $('div.tab-content').html()
  });
  localStorage.setItem("tableList", JSON.stringify(inititalTable));

}

});

如何在重新加载页面时显示行表而不删除initialTable 代码?

JSFiddle Demo

0 个答案:

没有答案