Add row number column to jquery datatables

2019-01-22 00:41发布

I want jQuery datatables to automatically create row number column in the first column like datagrid in VB.

It looks like this:

enter image description here

Anyone knows how to do this?

3条回答
做个烂人
2楼-- · 2019-01-22 01:09

Just write a render function:

{
    "data": "id",
    render: function (data, type, row, meta) {
        return meta.row + meta.settings._iDisplayStart + 1;
    }
}
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-22 01:13

You just define an empty column in aoColumns.

Then in fnRowCallback function you just edit the column how you like. This callback is run every time new row is created.

Basicly if your first column has the row number, you could just do this in fnRowCallback:

var index = iDisplayIndex +1;
$('td:eq(0)',nRow).html(index);
return nRow;
查看更多
劫难
4楼-- · 2019-01-22 01:20

As I commented, both @Pehmolelu and @Tao Wang's answer was not working well for me. I had to go with what the DataTables's Index Column advises: https://datatables.net/examples/api/counter_columns.html

Note that in case of me even the column configuration is coming down through an API call of my webapp server (and sometimes I have row counters, sometimes don't), there are 3 system column before this counter column, hence the column index is 3, but you need to adjust it to fit your needs.

t.on('order.dt search.dt', function () {
    t.column(3, {search:'applied', order:'applied'}).nodes().each( function (cell, i) {
        cell.innerHTML = i+1;
    });
}).draw();

Also, if your solution is not as complex as mine the link above also shows how you add that column in an unsortable + unsearchable way (again you need to adjust the column index to your needs):

var t = $('#example').DataTable({
    "columnDefs": [{
        "searchable": false,
        "orderable": false,
        "targets": 3
    }],
    "order": [[4, 'asc']]
});

There's also a plugin you may want to utilize instead of your own code.

查看更多
登录 后发表回答