想要在Datatables中进行排序时触发自定义事件

use*_*427 6 javascript sorting jquery datatables

当用户单击列标题进行排序时,我想触发自己的事件.我不想让它排序.我一直在做研究,并没有看到一个很好的方法来做到这一点.

我可以绑定sort事件来做我自己的事情,但仍然会发生这种情况.我不想要这个.如果我禁用排序,那么sort事件永远不会触发,所以这也不起作用.

我可以禁用排序,然后尝试捕获标题上的点击事件,但我希望有更好的方法来做到这一点.有人有主意吗?

dav*_*rad 12

很容易.你只需取消绑定click.DT处理程序并添加自己的.你不必禁用排序.

<table id="example">
<thead>
   <th id="id">ID</th>
   <th id="username">Username</th>
</thead>
<tbody>
    <tr><td>1</td><td>A test</td></tr>
    <tr><td>2</td><td>B test</td></tr>
    </tbody>       
</table>
Run Code Online (Sandbox Code Playgroud)

JavaScript的

$(document).ready(function(){
    //init datatables
    var table = $('#example').dataTable();

    //unbind sort event, prevent sorting when header is clicked
    $('#example th').unbind('click.DT');

    //create your own click handler for the header
    $('#example th').click(function(e) {
        alert('Header '+$(this).attr('id')+' clicked');
        //here you can trigger a custom event
    });

    //if you afterwards want to restablish sorting triggered by a click event 
    //here header "username" from example above
    table.fnSortListener(document.getElementById('username'), 1);
});
Run Code Online (Sandbox Code Playgroud)

注意:数据表中没有专门的"排序" - 事件.Allan Jardine提到它可能会出现在未来的版本2. http://datatables.net/forums/discussion/5141/capturing-sort-event-on-table-heading/p1