我正在使用数据表 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
});
}
});
Run Code Online (Sandbox Code Playgroud)
JSFiddle在这里:http : //jsfiddle.net/07nk5wob/33/
我究竟做错了什么?
请参阅我的更正答案。
基本上,您需要使用type: "num"数字数据显式声明列数据类型,否则它可能默认为字母排序。
{
"data": "outcomes_str",
"title": 'Games won',
"type": "num",
"render": {
"_": "display",
"sort": "sort"
}
}
Run Code Online (Sandbox Code Playgroud)
有关代码和演示,请参见更新的jsFiddle。