Jquery数据表在json表中添加新行

时间:2017-02-27 12:46:14

标签: javascript jquery json datatable

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

我想在我的json表中添加一个新行。

我无法理解为什么不这样做?

jsfiddle:http://jsfiddle.net/f7debwj2/17/

HTML:

<table id="example" class="display" width="100%" cellspacing="0">
  <thead>
    <tr>
      <th>order</th>
      <th>name</th>
      <th>country</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>
    </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/clmDuyndua?indent=2';
  var table = $('#example').DataTable({
    ajax: url,
    rowReorder: {
      dataSrc: 'order',
    },
    columns: [{
      data: 'order'
    }, {
      data: 'name'
    }, {
      data: 'place'
    }]
  });
  // add row
  $('#addRow').click(function() {
    //t.row.add( [1,2,3] ).draw();
    var rowHtml = $("#newRow").find("tr")[0].outerHTML
    console.log(rowHtml);
    dt.row.add($(rowHtml)).draw();
  });
});

2 个答案:

答案 0 :(得分:3)

您可以在documentation中看到,您需要更改此行:

dt.row.add($(rowHtml)).draw();

为:

table.row.add($(rowHtml)).draw();

updated fiddle

答案 1 :(得分:1)

你的实际错误是 未捕获的ReferenceError:未定义dt

只需在按钮点击事件中更改table.row.add($(rowHtml))。draw()而不是dt.row.add($(rowHtml))。draw()。