Jquery Datables删除并添加新行

时间:2017-02-27 15:58:48

标签: javascript jquery datatables

我正在使用:jquery.dataTables.js来自:https://datatables.net

问题:

如果删除某些行并在之后添加新行,则删除的行将返回。

如果我添加1行并删除此行,则在添加另一行后,插入2而不是1

所以我试图存档的是:

删除的行不会被删除。

如果我添加新行只添加1,如果我之前删除了一行并不重要。

HTML:

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>order</th>
      <th>name</th>
      <th>country</th>
      <th>delete</th>
    </tr>
  </thead>
</table>

<button id="addRow">Add New Row</button>
<table id="newRow">
  <tbody>
    <tr>
      <td>Line 2
        <input type="hidden" value="2" /> </td>
      <td>DVap
        <input type="hidden" value="DVap" /> </td>
      <td>
        <input type="text" value="22" /> </td>
      <td>
        <i class="fa fa-minus-square" aria-hidden="true"></i> </td>
    </tr>
  </tbody>
</table>

jquery的:

  $(document).ready(function() {
    var dt = $('#example').dataTable();
    dt.fnDestroy();

  });
  $(document).ready(function() {
    var url = 'http://www.json-generator.com/api/json/get/bQzyuEGndu?indent=2';
    var table = $('#example').DataTable({
      ajax: url,
      rowReorder: {
        dataSrc: 'order',
      },
      columns: [{
        data: 'order'
      }, {
        data: 'place'
      }, {
        data: 'name'
      }, {
        data: 'delete'
      }],
      "fnDrawCallback": function(oSettings) {
        $("i.fa.fa-minus-square").click(function(event) {
          $(this).closest("tr").remove();
        });
      }
    });
    // add row
    $('#addRow').click(function() {
      //t.row.add( [1,2,3] ).draw();
      var rowHtml = $("#newRow").find("tr")[0].outerHTML
      console.log(rowHtml);
      table.row.add($(rowHtml)).draw();
    });
  });

jsfiddle:http://jsfiddle.net/5L2qy092/3/

1 个答案:

答案 0 :(得分:1)

你应该使用DataTables api删除/删除行,其他明智的DataTables不知道实际删除了什么。

您也需要使用initComplete,因为fnDrawCallback会在每次表格绘制时触发,因此您不希望每次都添加click event处理程序

 "initComplete": function(oSettings) {
    $("i.fa.fa-minus-square").click(function(event) {
      table.row( $(this).closest('tr') ).remove().draw();
    });
  }

工作JSFIDDLE

修改

使用jquery delegate click动态添加行

 "initComplete": function(oSettings) {
    $(this).on("click", "i.fa.fa-minus-square", function(event) {
      table.row( $(this).closest('tr') ).remove().draw();
    });
  }
相关问题