在两个单独的JS DataTable中对两个不同的列索引进行排序

时间:2019-03-07 18:19:58

标签: javascript sorting datatables

我有一个站点使用DataTables来格式化同一页面上的两个表。目前,我可以显示和使用两个表(请参见下文),但是我不能在单独的索引处单独订购两个表。一个表有8列,另一个表有11列,我想按最后一列对它们进行排序。有没有办法在初始化期间或之后对它们进行排序?

示例按第8列对两个表进行排序:

$('table.display').DataTable({
    dom: 'f<br/>Btipr',
    order: [[ 7, "asc" ]],
    buttons: [{
            extend: 'excelHtml5',
            text: 'Save Table Excel',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'csv',
            text: 'Save Table Csv',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'pdf',
            text: 'Save Table PDF',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'colvis',
            text: 'Columns',
            className: "btn btn-outline-dark"
    }]
});

1 个答案:

答案 0 :(得分:2)

不是使用类选择器,而是使用Id选择器分别为两个表编写代码,如下所示:

HTML:

<table class="display" id="table1Id"></table>
<table class="display" id="table2Id"></table>

JS:

$('table#table1Id').DataTable({
    dom: 'f<br/>Btipr',
    order: [[ 7, "asc" ]],
    buttons: [{
            extend: 'excelHtml5',
            text: 'Save Table Excel',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'csv',
            text: 'Save Table Csv',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'pdf',
            text: 'Save Table PDF',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'colvis',
            text: 'Columns',
            className: "btn btn-outline-dark"
    }]
});

$('table#table2Id').DataTable({
    dom: 'f<br/>Btipr',
    order: [[ 10, "asc" ]],
    buttons: [{
            extend: 'excelHtml5',
            text: 'Save Table Excel',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'csv',
            text: 'Save Table Csv',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'pdf',
            text: 'Save Table PDF',
            filename: input + "_Table",
            className: "btn btn-outline-dark"
        },{
            extend: 'colvis',
            text: 'Columns',
            className: "btn btn-outline-dark"
    }]
});