jQuery DataTables默认排序不起作用

12

我有一张四列的表格,我想让用户对前三列进行排序,但不包括第四列。这一点已经实现了。但我还希望第三列默认按升序排序。这部分没有生效,我无法让任何一列默认排序,并且也无法弄清楚我的语法有什么问题:

$(document).ready(function() {
$(".table-sortable").dataTable({
    aaSorting: [],
    bPaginate: false,
    bFilter: false,
    bInfo: false,
    bSortable: true,
    bRetrieve: true,
    aoColumnDefs: [
        { "aTargets": [ 0 ], "bSortable": true },
        { "aTargets": [ 1 ], "bSortable": true },
        { "aTargets": [ 2 ], "asSorting": [ "asc" ], "bSortable": true },
        { "aTargets": [ 3 ], "bSortable": false }
    ]
}); 
});

这是我一直在参考的资料:http://datatables.net/usage/columns


我发现正在发生的事情,现在它不允许在第三列上进行这种类型的排序。我尝试添加“desc”,“asc”,“asc”,但没有成功。 - turbo2oh
2个回答

36

这应该能帮助你得到你所需要的东西

$(document).ready(function() {
    $(".table-sortable").dataTable({
        aaSorting: [[2, 'asc']],
        bPaginate: false,
        bFilter: false,
        bInfo: false,
        bSortable: true,
        bRetrieve: true,
        aoColumnDefs: [
            { "aTargets": [ 0 ], "bSortable": true },
            { "aTargets": [ 1 ], "bSortable": true },
            { "aTargets": [ 2 ], "bSortable": true },
            { "aTargets": [ 3 ], "bSortable": false }
        ]
    }); 
});

关键是aaSorting选项。出于某些原因,它不在主要的用法页面中... 但你可以在这里找到它 http://datatables.net/ref


@turbo2oh:很高兴你已经让它工作了。DataTables是一个很棒的插件。 - BLSully
大家好,是否有人知道如何使用类名而不是列索引在aaSorting中使用aTargets? - Lim
2
我曾尝试过使用类名而不是列索引来排序,唯一有效的方法是使用以下代码:'aaSorting': [[$('.desc').index(), 'desc']]其中'.desc'是我想排序的列th上的类名。 - Tom Hartman
对我不起作用, 只有“bSortable”:true - 显示排序图标, “bSortable”:false - 不显示图标。 但功能无法正常工作。 - Suraj Sakhare
谢谢!我一直无法理解为什么“order”在这里(https://datatables.net/examples/basic_init/table_sorting.html)不能像预期的那样工作。但是aaSorting完美地达到了预期效果。感谢! - JohnGalt

3

这个方法对我很有用,谢谢。最初我使用的是'order':[2,'desc'],但它并没有起作用。正确的选项是aaSorting

例如:

$(document).ready(function() {
    $('#example1').DataTable({
        aaSorting: [[0, 'desc']]
    });
});

这不是一个答案,请将此文本作为评论添加。 - Ignacio Ara
谢谢您指出这一点。这确实有效。我能找到的“官方”文档显示“order”是正确的参数,但aaSorting对我有用。有人知道为什么“order”不起作用吗?文档有误吗? - JohnGalt
我已经有一段时间没有使用数据表了,但是据我记得,aaSorting是在1.10之前的版本中使用的,而order则是在1.10及以上版本中使用的。 - BLSully

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