jQuery数据表中的列排序

我已经完成了jQuery datatable插件中的列排序以及控制它的各种方法。我有一个查询是可以控制排序,点击上箭头图标将按升序排序和向下箭头图标会按降序排序吗?

根据数据表版本,有两种方法可以做到这一点。

编辑数据表版本1.9或更低版本

您需要使用fnHeaderCallback 。 使用此回调,您可以编辑表头中的每个元素。

我已经为你创建了一个工作示例。 LIVE: http//live.datatables.net/oduzov代码: http//live.datatables.net/oduzov/edit#javascript,html

这是代码背后的代码(用于查看代码的开放代码段):

 $(document).ready(function($) { var table = $('#example').dataTable({ "fnHeaderCallback": function(nHead, aData, iStart, iEnd, aiDisplay) { // do this only once if ($(nHead).children("th").children("button").length === 0) { // button asc, but you can put img or something else insted var ascButton = $(document.createElement("button")) .text("asc"); var descButton = $(document.createElement("button")) .text("desc"); // ascButton.click(function(event) { var thElement = $(this).parent("th"); // parent TH element var columnIndex = thElement.parent().children("th").index(thElement); // index of parent TH element in header table.fnSort([ [columnIndex, 'asc'] ]); // sort call return false; }); descButton.click(function(event) { var thElement = $(this).parent("th"); var columnIndex = thElement.parent().children("th").index(thElement); table.fnSort([ [columnIndex, 'desc'] ]); return false; }); $(nHead).children("th").append(ascButton, descButton); } } }); }); 
   
Name Position Office Age Start date Salary
Name Position Office Age Start date Salary
Tiger Nixon System Architect Edinburgh 61 2011/04/25 $3,120
Garrett Winters Director Edinburgh 63 2011/07/25 $5,300