【发布时间】:2016-04-06 08:03:15
【问题描述】:
我有一个从 ajax 源获取数据的数据表,它目前按第 4 列降序排列。但是我有一个数据数组,我想对不作为列存在的表进行排序。
oTable = $('#Table').DataTable({
"scrollX": true,
stateSave: false,
"processing": true,
"serverSide": false,
"ajax": "scripts/SSP_enquiry.php",
select: true,
colReorder: true,
"columnDefs": [
{
"visible": false,
"searchable": false,
"targets": [9, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27]
},
{className: "word", "targets": [1]}
],
order: [4, 'desc'],
dom: '<"top">lrt<"bottom"pB><"clear">',
responsive: false,
buttons: [
'excel'
]
});
我的函数使用 Moment.JS 在表中的日期(存在于第 4 列)和今天的日期之间进行比较。然后它将天数差异推送到一个名为 dArray 的数组中。
我的数组对每个值都有一个索引,该索引应该与表中的行相关。
所以我要做的是使用索引和值根据dArray中的值对当前表进行排序
function dateGet() {
var idx = oTable
.columns( 4 )
.data()
.eq( 0 );// Reduce the 2D array into a 1D array of data
//console.log(idx);
var dArray = [];
var today = moment();
$.each(idx, function(index,value) {
var tempDate = moment(value);
var deadlineDiff = tempDate.diff(today, 'days');
dArray.push(index,deadlineDiff);
console.log(dArray);
})
}
dArray 的示例
[0, 6]
[1, 0]
[2, -0]
[3, -0]
[4, -1]
[5, -6]
[6, -7]
[7, -7]
[8, -11]
[9, -12]
[10, -12]
[11, -12]
[12, -13]
更新
我添加了一个值默认为 0 的新列,因此我现在需要根据截止日期差异值数组分配值。他们需要匹配相应行的ID。
result[j][0] 会给我数组中的 ID
result[j][1] 会给我数组中的差值
function dateGet() {
var dArray = [];
var today = moment();
var ID = oTable
.columns(0)
.data()
.eq(0);
var dDate = oTable
.columns(4)
.data()
.eq(0);// Reduce the 2D array into a 1D array of data
$.each(dDate, function (index, value) {
var tempDate = moment(value);
var deadlineDiff = Math.abs(tempDate.diff(today, 'days'));
dArray.push(deadlineDiff);
});
var result = $.map(ID, function (el, idx) {
return [[el, dArray[idx]]];
});
oTable.rows().every(function (rowIdx, tableLoop, rowLoop) {
var data = this.data();
for (var j = 0; j < result.length; j++) {
if (data[0] == result[j][0]) {
//in here the ID in the table and the ID in the array
// match, I need to iterate through rows and assign the value
//in the array to column 28's cell
}
}
});
}
【问题讨论】:
-
作为一个建议......在第 4 列的渲染函数中,您能否将数据属性添加到包含您的日期的跨度?然后按日期而不是日期本身订购?
-
hmmm 所以你建议,将数组中的值添加到相应的行/列索引,然后对数据属性进行排序。我不知道我能不能做到,你有例子吗?
-
@annoyingmouse 是对的,甚至更好 - 当
render()方法需要sort或filter值时,只需返回数组值。 -
添加了示例。我更喜欢
columns的粒度控制而不是columnDefs。虽然我没有尝试过,但应该很容易转换。
标签: jquery datatables datatables-1.10