質問

I'm trying to get jQuery dataTables to sort my numeric column by custom values. I've read all the threads about numeric sorting, but couldn't find a working solution for my problem, yet. I'm storing my numbers in an jQuery data attribute called sort-count

This is my dataTables initialization:

$('.wp-list-table').dataTable({
    "aoColumns": [
        null,
        null,
        null,
        { "sType": "numeric", "sSortDataType": "numeric-data-attribut" },
        { "sType": "numeric", "sSortDataType": "numeric-data-attribut" },
        { "bSortable": false, "bSearchable": false },
    ],
    "bJQueryUI":true,
    "bPaginate":true,
    "sPaginationType":"full_numbers"
});

And this is my custom afnSortData function to catch the values before sorting:

jQuery.fn.dataTableExt.afnSortData['numeric-data-attribut'] = function ( oSettings, iColumn )
{
    var aData = [];
    jQuery( 'td:eq('+iColumn+')', oSettings.oApi._fnGetTrNodes(oSettings) ).each( function () {
        aData.push( parseInt( jQuery(this).attr('data-sort-count'), 10 ) );
    } );

    console.log(aData);

    return aData;
};

The console.log(aData) is showing the following output when clicking multiple times on the column to sort it. As you can see, it fetches the right values, they are all numeric, but it is sorting them completely randomly.

output of console log

I've tried for numerous hours, but just can't get it working.

役に立ちましたか?

解決

... 7 hours later ...

It's a bug that occurs when you use newer versions of jQuery with dataTables. Apparently the returned selection is now ordered by DOM occurence and not by the order of the elements in the array which is returned by the _fnGetTrNodes function anymore.

The sample for using a custom afnSortData function in the dataTables documentation is outdated and doesn't work with newer jQuery versions.

Working version looks like this:

jQuery.fn.dataTableExt.afnSortData['numeric-data-attribut'] = function ( oSettings, iColumn )
{
    return jQuery.map( oSettings.oApi._fnGetTrNodes(oSettings), function (tr) {
        var v = jQuery( 'td:eq('+iColumn+')', tr);
        return parseInt( jQuery(v).attr('data-sort-count'), 10 );
    } );
};
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top