jQuery数据表中的列排序

Niv*_*Rai 3 jquery datatables

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

Nik*_*car 6

根据datatables版本,有两种方法可以做到这一点.

编辑Datatables版本1.9或更低版本

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

我已经为你创建了一个工作示例.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);
      }
    }
  });
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://legacy.datatables.net/release-datatables/media/js/jquery.dataTables.js"></script>
<table id="example" class="display" width="100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Age</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>61</td>
      <td>2011/04/25</td>
      <td>$3,120</td>
    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Director</td>
      <td>Edinburgh</td>
      <td>63</td>
      <td>2011/07/25</td>
      <td>$5,300</td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

对于Datatables版本1.10及更高版本

回调有一个新名称,它只是headerCallback.其他一切都是一样的,所以使用传统api的新回调.