【问题标题】:How to get the sorted column value in datatable?如何获取数据表中的排序列值?
【发布时间】:2013-05-31 15:05:05
【问题描述】:

我有一个数据表。我想在对数据表的列进行排序时触发一个事件。 这是我的代码。

var productTable = $('#example').dataTable({
    "bFilter": true,
    "bJQueryUI": true,
    "bSort": true,
    "bLengthChange": true,
    "iDisplayLength": -1,
    "aLengthMenu": [[-1, 25, 50, 100], ["All", 25, 50, 100]],
    "sPaginationType": "full_numbers",
    "bPaginate": true
});   
$('#example').bind('sort',   function () { /* Here I want to get the value of the sorted coumn */});

在绑定函数中,我想要排序列的名称。谁能帮我找出来?

【问题讨论】:

  • 没有使用过数据表插件,但是你可以使用this或者$(this)获取触发事件的元素,将其转换为jquery对象。
  • 已经试过 $(this),它给了我整张桌子。

标签: jquery sorting datatable


【解决方案1】:

排序事件有两个参数。事件和数据表本身。使用 datatable 参数,您可以读取当前 aaSorting 字段并确定列排序的索引和列排序的方向。通过列排序的索引,您可以查找列并使用数据表 aoColumns 字段获取正在排序的列的名称。

.bind('sort', function (e, dt) {
    var direction = dt.aaSorting[0][1];
    var columnIndex = dt.aaSorting[0][0];
    var columnName = dt.aoColumns[columnIndex].sTitle;
});

【讨论】:

    【解决方案2】:

    引用 DataTable 的 API 参考:

    fnSortListener 将排序侦听器附加到给定列的元素

    输入参数:

    {node}: the element to attach the sort listener to
    {int}: the column that a click on this node will sort on
    {function}: callback function when sort is run
    

    返回参数:

    $(document).ready(function() {
      var oTable = $('#example').dataTable();
    
      // Sort on column 1, when 'sorter' is clicked on
      oTable.fnSortListener( document.getElementById('sorter'), 1 );
    } );
    

    因此,基本上,您必须将侦听器绑定到此事件,并且您将获得列的索引。然后你必须查一下它的名字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-08
      相关资源
      最近更新 更多