如何在DataTables中使用正交数据进行排序?

5
我正在使用 DataTables v1.10。当列中显示的值不是数字时,我想使该列按数字值进行排序。
我了解到需要使用 正交数据 来实现此功能,如 此处所述
但是,我的排序函数无法正常工作。这是我的代码:
var myData = [{
    'country': 'France',
        'all_games': 7,
        'won_games': 4
}, {
    'country': 'England',
        'all_games': 13,
        'won_games': 13
}, {
    'country': 'Germany',
        'all_games': 2,
        'won_games': 0
}];
var columns = [{
    "data": "country",
        "title": "Country"
}, {
    "data": "outcomes_str",
        "title": 'Games won',
        "render": {
        "_": "display",
            "sort": "sort"
    }
}];
$.each(myData, function (i, d) {
    d.outcomes_str = {};
    d.outcomes_str.sort = (d.all_games > 0) ? (d.won_games / d.all_games) * 100 : 0;
    d.outcomes_str.display = d.won_games + '/' + d.all_games + ' (' + Math.round(d.outcomes_str.sort * 10) / 10 + '%)';
    console.log(d.outcomes_str);
});
drawTable(myData, 'localTable');

function drawTable(data, tableId) {
    var html = '<table class="table table-bordered table-hover ';
    html += '" cellspacing="0" width="100%" id="myTable"></table>';
    $('#table').append(html);
    $("#myTable").DataTable({
        data: data,
        columns: columns,
        paging: false
    });
}
});

这里是JSFiddle链接:http://jsfiddle.net/07nk5wob/33/

我做错了什么?

1个回答

9

请查看我更正后的答案

基本上,对于数字数据,您需要使用type: "num"显式声明列数据类型,否则它可能默认为按字母顺序排序。

{
    "data": "outcomes_str",
    "title": 'Games won',
    "type": "num",
    "render": {
        "_": "display",
        "sort": "sort"
    }
}

请查看更新的 jsFiddle 代码和演示:链接

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