【问题标题】:Want to fire a custom event when trying to sort in Datatables想要在数据表中排序时触发自定义事件
【发布时间】:2013-06-25 02:52:07
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript jquery sorting datatables


    【解决方案1】:

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

    【讨论】:

    • 嗯。您使用的是哪个版本的数据表?在这里工作,1.9.xx
    • 多么有趣,必须是特定于版本的。使用.unbind('...') 非常适合我。但是,使用 fnSortListener(... 不会将排序重新绑定到列。
    猜你喜欢
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多