jQuery数据表格中的列排序

3

我已经了解了jQuery datatable插件中的列排序和各种控制方式。我有一个问题就是,是否可以通过点击向上箭头图标实现升序排序,而点击向下箭头图标实现降序排序?


你能告诉我箭头(向上、向下)是否同时可见,还是只有一个可见? - Nikola Loncar
1个回答

6

有两种方法可以做到这一点,具体取决于使用的 datatables 版本。

适用于 Datatables 1.9 或更早版本的情况

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

我为您创建了一个可工作的示例。 实时演示: 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);
      }
    }
  });
});
<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>

适用于Datatables 1.10及更高版本

回调函数有一个新名称,就是headerCallback。其他所有内容都保持不变,因此请使用新的回调函数而不是旧的API。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接