如何简单地按数据表的最后一列排序

How to simply sort by the last column of datatable

我真的是 dataTable 的新手,我只需要一个简单的解决方案:

var initBasicTable = function() {

    var table = $('#basicTable');

    var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [[0,'desc']]
    };

    table.dataTable(settings);
    $('#basicTable input[type=checkbox]').click(function() {
        if ($(this).is(':checked')) {
            $(this).closest('tr').addClass('selected');
        } else {
            $(this).closest('tr').removeClass('selected');
        }

    });

}

这是有效的,默认情况下对第一列进行排序。

但我读到将 "order": [[0,'desc']] 中的 0 更改为负数将从右侧的列开始排序。然而这个:

var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [[-1,'desc']]
};

抛出错误,我不知道从哪里继续。

我知道 dataTable 真的很强大,但是, this is no what I was looking for but plenty already

'Sort by last(-1) column' 什么都没有?我感到迷茫。任何人?

只需使用 dataTables 中的重新绘制功能即可:

table.order([0, 'desc']).draw();

并且不要对列索引使用负值。只使用积极的。 the api 这里没有提到可排序列的负列索引。

如果您现在不能关注我,请阅读:“https://datatables.net/reference/api/order%28%29

事实证明并不难,需要一些变通:

var table = $('#basicTable');
    var index = $(table).find('th:last').index();
    var settings = {
        "sDom": "t",
        "sPaginationType": "bootstrap",
        "destroy": true,
        "paging": false,
        "scrollCollapse": true,
        "order": [
            [index, "desc"]
        ]
    };

这将获取最后一个 'column' 的索引并首先对其进行排序。感谢大家的帮助。

您可以像这样初始化 table 以按最后一列排序

$('.table').DataTable().columns(-1).order('desc').draw();

查看详情this