javascript 想要在数据表中排序时触发自定义事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17345945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Want to fire a custom event when trying to sort in Datatables
提问by user1652427
When the user clicks on a column header to sort, I want to fire my own event. I DO NOT want it to sort. I've been doing research, and don't see a good way to do this.
当用户单击列标题进行排序时,我想触发自己的事件。我不希望它排序。我一直在做研究,并没有看到一个好的方法来做到这一点。
I can bind on the sort event to do my own stuff, but the sort still happens. I don't want this. If I disable sorting, then the sort event never fires, so this does not work either.
我可以绑定排序事件来做我自己的事情,但排序仍然发生。我不要这个。如果我禁用排序,则排序事件永远不会触发,因此这也不起作用。
I could disable sort and then try and capture click events on the header, but I was hoping there would be a better way to do this. Anyone have any ideas?
我可以禁用排序,然后尝试捕获标题上的点击事件,但我希望有更好的方法来做到这一点。有人有想法么?
回答by davidkonrad
Very easy. You just unbind the click.DT handler and add your own. You dont have to disable sorting.
很简单。您只需取消绑定 click.DT 处理程序并添加您自己的。您不必禁用排序。
example
例子
<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
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);
});
Note: There is no dedicated "sort"-event in datatables. Allan Jardine mention it may come in a future version 2. http://datatables.net/forums/discussion/5141/capturing-sort-event-on-table-heading/p1
注意:数据表中没有专门的“排序”事件。Allan Jardine 提到它可能会在未来的版本 2 中出现。http://datatables.net/forums/discussion/5141/capturing-sort-event-on-table-heading/p1