在dataTables库中加载数据时,添加新列以进行编辑/删除

时间:2018-11-04 12:25:42

标签: javascript datatables server-side

我有一个 dataTables 表,其数据通过ajax调用加载。每行有5列。配置如下:

<table id="table" class="table table-bordered table-hover" style="width: 100%">
  <thead>
    <tr>
      <th>@Html.DisplayNameFor(model => model.FirstName)</th>
      <th>@Html.DisplayNameFor(model => model.LastName)</th>
      <th>@Html.DisplayNameFor(model => model.PersonnelId)</th>
      <th>@Html.DisplayNameFor(model => model.NationalId)</th>
      <th>@Html.DisplayNameFor(model => model.Companies)</th>
      <th>Operations</th>
    </tr>
  </thead>
</table>

对于初始化,我使用:

var table = $('.table').DataTable({
    "proccessing": true,
    "serverSide": true,
    "ajax": {
        url: "server_api.php",
        type: 'POST'
    },
    "columns": [
        { "data": "FirstName" },
        { "data": "LastName" },
        { "data": "PersonnelId" },
        { "data": "NationalId" },
        { "data": "Companies" }
    ]
});

考虑到每行都有一个 Id ,如何在 operations 列中为每行添加Delete / Edit

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。要将数据添加到其他列,您需要

  1. 在初始化时添加一列,
  2. rowCallback 函数中填充列单元格。

代码是:

var table = $('.table')
                .DataTable({
                    "proccessing": true,
                    "serverSide": true,
                    "ajax": {
                        url: "server_api.php",
                        type: 'POST'
                    },
                    "columns": [
                        { "data": "FirstName" },
                        { "data": "LastName" },
                        { "data": "PersonnelId" },
                        { "data": "NationalId" },
                        { "data": "Companies" },
                        { "render" : function() {return ""; }
                    ],
                    "rowCallback": function (row, data) {
                        var additionalColIdx = 5; // Index of new column
                        $(`td:eq({additionalColIdx})`, row).html("<a href=\"edit.php/" + data.Id "\">Edit</a>" + " / " +
                                "<a href=\"delete.php/" + data.Id + "/" + "\">Delete</a>");
                    }
                });