jQuery Datatables:添加额外列

33

场景

我第一次使用(@版本1.9.4)向用户显示数据。我成功通过ajax检索到数据并将其绑定到datatable上。

现在,我想添加额外的列以让用户处理记录。为了简单起见,目标是添加一个按钮和一个onclick处理程序,以检索“点击”记录的数据。

按照我的计划,我会将与“点击”记录对应的json项目绑定到onclick处理程序上。

到目前为止,如果我向DOM添加一个附加的TH用于操作列,则datatables代码会出现错误:

Requested unknown parameter '5' from data source for row 0

问题

如何设置自定义列?如何使用HTML填充它们的内容?


这是我的实际配置。

HTML

<table id="tableCities">
    <thead>
        <tr>
            <th>country</th>
            <th>zip</th>
            <th>city</th>
            <th>district code</th>
            <th>district description</th>
            <th>actions</th>
        </tr>
    </thead>
    <tbody></tbody>
</table>

Javascript

$('#tableCities').dataTable({
    "bPaginate": true,
    "bLengthChange": false,
    "bFilter": true,
    "bSort": true,
    "bInfo": false,
    "bAutoWidth": true
    , "bJQueryUI": true
    , "bProcessing": true
    , "bServerSide": true
    , "sAjaxSource": "../biz/GetCitiesByZip.asp?t=" + t
});

示例Json结果

{
    "aaData":
    [
        [
            "IT",
            "10030",
            "VILLAREGGIA",
            "TO",
            "Torino"
        ],
        [
            "IT",
            "10030",
            "VISCHE",
            "TO",
            "Torino"
        ]
    ],
    "iTotalRecords": 2,
    "iTotalDisplayRecords": 2,
    "iDisplayStart": 0,
    "iDisplayLength": 2
}

编辑

Daniel 是正确的。解决方案是在 aoColumnDefs 中设置自定义列,指定 mDatamRender 属性。特别地,mRender 允许定义自定义的 HTML 和 JavaScript。

/* inside datatable initialization */
, "aoColumnDefs": [
   {
        "aTargets": [5],
        "mData": null,
        "mRender": function (data, type, full) {
            return '<a href="#" onclick="alert(\''+ full[0] +'\');">Process</a>';
        }
    }
 ]

1
对我有效,每行附加HTML链接/按钮都能带上“获取行ID值”的话,+1。 - bungdito
4个回答

33

您可以像这样以不同的方式定义列

"aoColumns": [
        null,
        null,
        null,
        null,
        null,
        { "mData": null }
    ]

或者这个

"aoColumnDefs":[
    {
        "aTargets":[5],
        "mData": null
    }
]

这里有一些文档:Columns

看一下这个DataTables AJAX source example - null data source for a column

请注意,在 DataTables 1.9.2之前,mData 被称为 mDataProp。更改名称反映了此属性的灵活性,并与 mRender 的命名保持一致。如果给出 'mDataProp',则 DataTables 仍将使用它,因为如果需要,它会自动将旧名称映射到新名称。

另一个解决方案/变通方法是添加 '5' 参数...

例如在每一行上添加额外的 ""

像这样:

    [
        "IT",
        "10030",
        "VILLAREGGIA",
        "TO",
        "Torino",
        ""
    ],
    [
        "IT",
        "10030",
        "VISCHE",
        "TO",
        "Torino",
        ""
    ]

简单来说,第五个缺失的参数只对应于操作列。向数据源添加一个“_empty_”字段似乎是一种解决方法,而不是答案。 - Alberto De Caro

9

使用"defaultContent"。 - PartialOrder

6

在此发布答案,以展示需要定义aoColumnDefs的位置。我从这个问题中得到了帮助,但是我花了一段时间才找到放置aoColumnDefs的位置。此外,还添加了单击事件的功能。

$(document).ready(function() {
  var table = $('#userTable').DataTable( {
        "sAjaxSource": "/MyApp/proctoring/user/getAll",
        "sAjaxDataProp": "users",
        "columns": [
                    { "data": "username" },
                    { "data": "name" },
                    { "data": "surname" },
                    { "data": "status" },
                    { "data": "emailAddress" },
                    { "data" : "userId" }
                  ],
        "aoColumnDefs": [
           {
                "aTargets": [5],
                "mData": "userId",
                "mRender": function (data, type, full) {
                    return '<button href="#"' + 'id="'+ data + '">Edit</button>';
                }
            }
         ]
    } );

    $('#userTable tbody').on( 'click', 'button', function () {
        var data = table.row( $(this).parents('tr') ).data();
        console.log(data);
        $('#userEditModal').modal('show');
    });

} );

0

操作

 [HttpGet]
        public JsonResult Roles()
        {
            var data = _accountService.GetRoles().Result;
            return Json(data);
        }

CDN
<link rel="stylesheet"
 href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.css" /> 
 <script
 src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.js"></script>

Html

<table class="table table-hover" id="table">
                  <thead>
                      <tr>
                          <th>Code</th>
                          <th>Name</th>
                          <th></th>
                      </tr>
                  </thead>
              </table>

数据表代码

<script>
        $(document).ready(function(){
            debugger;
            $("#table").dataTable({
                "ajax": {
                    "url": "/Admistration/Roles",
                    "type": "GET",
                    "dataSrc": "",
                     "datatype": "json"
                },
               "columns": [
                    { "data": "code", "autoWidth": true },
                    { "data": 'name', "autoWidth":true},
                    { "render": function (data, type, full) { return "<a  class='btn btn-danger' onclick=DeleteCustomer('" + full.code + "') ><i class='bi bi-trash3-fill'></i></a>   <a href='#' class='btn btn-primary' onclick=DeleteCustomer('" + full.code + "'); ><i class='bi bi-pencil-square'></i></a>" } }
                ]
            });
        })
   
    </script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接