在一个项目/小提琴中组合'添加表'和'保存副本行'

问题描述 投票:2回答:1

我有2个小提琴。

  • 在第一个(JSFiddle 1)中,我创建了一个新表并保存到localStorage中
  • 在第二个(JSFiddle 2)中,我创建了一个复制行功能(选定行并将其复制到选定的表)。

我的目标是将两个小提琴合二为一,这样你就可以:

  • 添加新表[可在JSFiddle 1上使用]
  • 添加表时,有一个'复制到表1'选项[可在JSFiddle 2上使用]
  • 可以选择行,然后使用该选项将其复制到选定的表中。 [可在JSFiddle 2上使用]

我需要删除它,并使用代码$('#table' + localStorage.Index).dataTable({...})将其替换为新的表格功能

 $('#table2').dataTable({
    "data": localStorage.getItem('dataSet_table2') ? JSON.parse(localStorage.getItem('dataSet_table2')) : [], //changed here
    "columns": [{
      "title": "First Name"
    }, {
      "title": "Last Name"
    }, {
      "title": "Action"
    }],
    "bStateSave": true,
    "stateSave": true,
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": false,
    "bInfo": false,
    "bAutoWidth": false
  });

我花了很多时间在这上面但是我遇到了一些问题:

  • 重新加载时,我无法第二次选择行。
  • 无法复制行。

我的工作小提琴[更新2]:https://jsfiddle.net/59u53rvn/2/

var mainTable = $("#mainTable").dataTable({
  "bStateSave": true,
  "stateSave": true,
  "bPaginate": false,
  "bLengthChange": false,
  "bFilter": false,
  "bInfo": false,
  "bAutoWidth": false
});

/*SELECT OPTION */
mainTable.on('click', 'tr', function() {
  var $row = $(this),
    isSelected = $row.hasClass('selected')
  $row.toggleClass('selected')
    .find(':checkbox').prop('checked', !isSelected);
});

$('#copyToTable1,#copyToTable2').on('click', function() {

  let $elem = $(this);
  var table = $("#table" + $elem.attr('id').replace(/[a-zA-Z]/ig, ''));
  var tbl_id = table.attr('id');

  var $row = mainTable.find(".selected");
  if (!$row.length) {
    console.log('You must select some rows to copy first');
    return;
  } else {
    var r = confirm("Copy to table " + tbl_id + "?");
    var table_to_copy = table.dataTable();
    if (r == true) {
      copyRows(mainTable, table_to_copy);
      console.log("Copied!");
      setTimeout('console.clear()', 2000);
    }
  }
});

function copyRows(fromTable, toTable) {
  var $row = fromTable.find(".selected"),
    storageName = 'dataSet_' + toTable.attr('id'), //added this line 
    dataSet = localStorage.getItem(storageName) ? JSON.parse(localStorage.getItem(storageName)) : []; //added this line 

  $.each($row, function(k, v) {
    if (this !== null) {
      addRow = fromTable.fnGetData(this);
      toTable.fnAddData(addRow);
      dataSet.push(addRow); //added this line 
    }
  });

  localStorage.setItem(storageName, JSON.stringify(dataSet)); //added this line 
}

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {
  function getTableList() {
    var addTable = '<button id="copyToTable' + localStorage.Index + '" >copyToTable ' + localStorage.Index + '</button>' +
      '<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>Audience Name</th>' +
      '<th>Type</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({
      "data": localStorage.getItem('dataSet_table' + localStorage.Index) ? JSON.parse(localStorage.getItem('dataSet_table' + localStorage.Index)) : [], //changed here
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });
    alert("sucess create table");

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


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

  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({
      "data": localStorage.getItem('dataSet_table' + localStorage.Index) ? JSON.parse(localStorage.getItem('dataSet_table' + localStorage.Index)) : [], //changed here
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });
  } else {
    let inititalTable = [];
    inititalTable.push({
      table: $('div.tab-content').html()
    });
    localStorage.setItem("tableList", JSON.stringify(inititalTable));
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>

<input type="button" class="submitButton" value="ADD NEW TABLE">

<div class="tab-content">
  <div class="tab-pane" id="mainFolder">
    <h3>DEFAULT TABLE</h3>
    <div class="zf-table">
      <table id="mainTable" class="table table-bordered table-hover myFade">
        <thead>
          <tr>
            <th>Audience Name</th>
            <th>Type</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>Calvin</td>
            <td>Lookalike</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

</div>

问我没有解释过这个问题,我会在这里和小提琴中解决它。

javascript jquery html datatables jsfiddle
1个回答
1
投票

好的,我使用您的代码2作为起点,将代码1与代码2合并。

见工作示例:

https://jsfiddle.net/mgsrzzye/1/

首先,我们需要在页面加载时检查本地存储,如果存在则在页面上打印表格。

$(document).ready(function(){
        var localtbl = localStorage.getItem('tableList');

    var resultTable = [];
    if(localtbl !== undefined && localtbl !== ''){
    resultTable = JSON.parse(localtbl);
    }
        $.each(resultTable, function(i,v){
                $('#table1_wrapper').append(v.table);

    $('table[id^="table'+(i+2)+'"]').dataTable({
      "data": localStorage.getItem('dataSet_table' + (i+2)) ? JSON.parse(localStorage.getItem('dataSet_table' + (i+2))) : [], //changed here
      "columns": [{
        "title": "First Name"
      }, {
        "title": "Last Name"
      }, {
        "title": "Action"
      }],
      "bStateSave": true,
      "stateSave": true,
      "bPaginate": false,
      "bLengthChange": false,
      "bFilter": false,
      "bInfo": false,
      "bAutoWidth": false
    });

      })
})

然后,我们需要复制代码1以添加具有一些更改的新表。

/* CREATE TABLE FITURE */
$('.submitButton').click(function() {

  var tblcount = ($('table[id^="table"]').length + 1);

    var addTable = '<br><button class="btn btn-success" id="copyToTable'+tblcount+'"> Copy To Table '+(tblcount)+'</button>' +
    '<h3 style="color:red;">Table '+(tblcount)+'</h3>' +
      '<table id="table'+tblcount+'" class="table table-striped table-bordered" cellspacing="0" width="100%"></table>';
    var getTbl = localStorage.getItem("tableList");
    var resultTable = [];
    if(getTbl !== undefined && getTbl !== ''){
    resultTable = JSON.parse(getTbl);
    }
    let newtableHTML = addTable;
    resultTable.push({
      table: newtableHTML
    });
    // save the new resultFolder array
    localStorage.setItem("tableList", JSON.stringify(resultTable));

  //console.log(tblcount);
  $('#table' + (tblcount-1) + '_wrapper').after(addTable);

  $('#table' + (tblcount)).dataTable({
    "data": localStorage.getItem('dataSet_table' + tblcount) ? JSON.parse(localStorage.getItem('dataSet_table' + tblcount)) : [], //changed here
    "columns": [{
      "title": "First Name"
    }, {
      "title": "Last Name"
    }, {
      "title": "Action"
    }],
    "bStateSave": true,
    "stateSave": true,
    "bPaginate": false,
    "bLengthChange": false,
    "bFilter": false,
    "bInfo": false,
    "bAutoWidth": false
  });


}); // submitButton func

最后一个,我们需要使用body,因为有时候我们添加了动态表。

$('body').on('click', 'button[id^="copyToTable"]', function(){
  let $elem = $(this);
  var table = $("#table" + $elem.attr('id').replace(/[a-zA-Z]/ig, ''));
  var tbl_id = table.attr('id');

  var $row = mainTable.find(".selected");
  if (!$row.length) {
    console.log('You must select some rows to copy first');
    return;
  } else {
    var r = confirm("Copy to table " + tbl_id + "?");
    var table_to_copy = table.dataTable();
    if (r == true) {
      copyRows(mainTable, table_to_copy);
      console.log("Copied!");
      setTimeout('console.clear()', 2000);
    }
  }
})
© www.soinside.com 2019 - 2024. All rights reserved.