Ric*_*ard 3 javascript jquery datatables
我正在使用 DataTables 1.10 版。当列中显示的值不是数字时,我想让列按数值排序。
我可以看到我需要做的是data-sort为每个表格单元格添加一个属性。我已经尝试使用该createdRow方法添加它,但是虽然我可以在 HTML 中看到该属性,但它不是按数字排序的。
这是我的代码:
var data = [
{
'name': 'France',
'played': 1000,
'won': 11
},
{
'name': 'England',
'played': 1000,
'won': 100
},
{
'name': 'Germany',
'played': 1000,
'won': 109
}
];
$.each(data, function(i, d) {
d.won_percent = (d.won / d.played) * 100;
d.won_display = d.won + '/' + d.played;
d.won_display += ' (';
d.won_display += Math.round(d.won_percent * 10) / 10;
d.won_display += '%)';
});
var columns = [
{ "data": "name",
"title": "Country"
},
{ "data": "won_display",
"title": "Games won"
},
{ "data": null,
"title": "Notes",
"defaultContent": 'Some other text here, included just to test that responsive works'
}
];
var html = '<table class="table table-bordered table-hover" cellspacing="0" width="100%" id="myTable"></table>';
$('#table').html(html);
$("#myTable").DataTable({
data: data,
columns: columns,
order:[[1, "desc"]],
responsive: true,
paging: false,
searching: false,
createdRow: function (row, data, rowIndex) {
$.each($('td', row), function (colIndex) {
if (colIndex === 1) {
$(this).attr('data-order', data.won_percent);
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
如何让我的表按 的值排序d.won_percent?
请注意,我也在构建一个响应式表,这意味着我需要小心使用渲染事件。
JSFiddle在这里:http : //jsfiddle.net/07nk5wob/5/
这是一种本地方法
在数据表设置对象中添加此“columnDefs”对象
columnDefs: [
{
targets: [1], // cell target
render: function(data, type, full, meta) {
if(type === "sort") {
var api = new $.fn.dataTable.Api(meta.settings);
var td = api.cell({row: meta.row, column: meta.col}).node(); // the td of the row
data = $(td).attr('data-order'); // the data it should be sorted by
}
return data;
}
},
],
Run Code Online (Sandbox Code Playgroud)
这是一个工作小提琴:http://jsfiddle.net/07nk5wob/6/
解决方案
您可以使用正交数据,这是 jQuery DataTables 的术语,用于为显示、排序和过滤操作提供不同的数据。
您还需要使用type: "num".
$.each(data, function (i, d) {
d.won_percent = {
sort: (d.won / d.played) * 100
};
d.won_percent.display =
d.won + '/' + d.played +
' (' + Math.round(d.won_percent.sort * 10) / 10 + '%)';
});
// ... skipped ...
{
"data": "won_percent",
"title": "Games won",
"type": "num",
"render": {
"_": "display",
"sort": "sort"
}
},
Run Code Online (Sandbox Code Playgroud)
演示
有关代码和演示,请参阅更新的 jsFiddle。
链接