6

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

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

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

4

1 回答 1

13

很容易。您只需取消绑定 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>

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);
});

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

于 2013-06-27T15:08:21.910 回答