[英]jQuery Datatables: Sort on one column when clicking on another.
我有一個帶有日期和時間列的jQuery數據表:
Date Time Note
1/2/2015 10:02:03 Test
1/4/2915 02:12:32 Test
1/3/2015 02:05:03 Test
3/2/2015 11:02:03 Test
1/4/2015 01:02:13 Test
我想實施一種時間安排。 按時間排序時,我們首先需要按日期排序,然后按時間排序:
Date Time Note
1/2/2015 10:02:03 Test
1/3/2015 02:05:03 Test
1/4/2015 01:02:13 Test
1/4/2915 02:12:32 Test
3/2/2015 11:02:03 Test
我有以下代碼:
//jQuery datatable code
{ mData: 'date', sTitle: 'Date', sClass: "dtDate" },
{ mData: 'time', sTitle: 'Time', sClass: "dtTime", sType: "time-date-sort"},
{ mData: 'notes', sTitle: 'Notes' },
// More code...
jQuery.fn.dataTableExt.oSort['time-date-sort-asc'] = function(startTime, endTime) {
//Date and time sorts go here
return sortedVal;
};
jQuery.fn.dataTableExt.oSort['time-date-sort-desc'] = function (startTime, endTime) {
//Date and time sorts go here
return sortedVal;
};
我可以使用此功能按時間排序,但是如何先按日期排序? 我試圖弄清楚如何獲取表行中的日期值的引用(與該行中的時間值相關聯)。 例如, 如何我搶日期對象1/2/2015
進行,時間是該行10:02:03
? 好像我可以將自定義參數添加到oSort函數中一樣。 我應該使用jQuery.fn.dataTableExt.oSort
還是jQuery.fn.dataTableExt.afnSortData
更好的選擇?
要從其他列中獲取值以包含在您的自定義排序中,您必須創建一個自定義數據源排序插件。 下面將返回第0列和第1列中的值作為日期+時間字符串,即1/2/2015 10:02:03
:
$.fn.dataTable.ext.order['order-time-date-sort'] = function(settings, col) {
return this.api().row({order:'index'} ).nodes().map(function (tr, i) {
return $('td:eq(0)', tr).text()+' '+$('td:eq(1)', tr).text();
});
}
然后將上述order-date-time-sort
為time列的orderDateType
:
var table = $('#example').DataTable({
columnDefs : [
{ type: 'time-date-sort',
orderDataType: "order-time-date-sort",
targets: [1]
}
]
});
現在,也可以使用簡單的Date.parse()
來根據日期對時間進行排序:
jQuery.fn.dataTableExt.oSort['time-date-sort-pre'] = function(value) {
return Date.parse(value);
};
jQuery.fn.dataTableExt.oSort['time-date-sort-asc'] = function(a,b) {
return a-b;
};
jQuery.fn.dataTableExt.oSort['time-date-sort-desc'] = function(a,b) {
return b-a;
};
演示-> http://jsfiddle.net/4toLj9yn/
注意 :如果您在性能方面遇到問題,則可能是由於一個巨大的表而發生的,您應該“緩存” order-time-date-sort
的結果(只需將結果存儲在變量中)。 您也可以考慮使用完全不同的方法- 正交數據 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.