排序表后不会触发jQuery click()事件

加载页面时,如果单击某一行,则会记录到clicked的控制台。

但是,如果您对表进行排序(单击表标题),如果您尝试单击行,则单击tr上的事件不会被触发。

我正在使用这个插件: tablefixedheader

jQuery的

 $(document).ready(function(){ $("table.ex").fixheadertable({ caption : 'Tarefas Disponíveis', showhide : false, height : '265', zebra : true, zebraClass : 'ui-state-default', sortable : true, sortedColId : 0, dateFormat : 'Y/m/d', pager : true, rowsPerPage : 25, colratio : [110,150], minColWidth : 110, resizeCol : true }); // problem with this click // The event isn't triggered: $("table.ex tr").click(function(){ console.log('clicked'); }); }); 

演示 http://jsfiddle.net/QpU3c/

您应该使用事件委派 ,因为插件会更改原始的tr元素,因此它们将丢失其附加的事件处理程序。 处理程序应该附加在表本身上,因为它肯定没有改变。

 $("table.ex").on('click', 'tr', function(){ console.log('clicked'); }); 

jsFiddle演示

 $("table.ex").on('click', 'tr', function(){ console.log('clicked'); }); 

DEMO


注意

您需要委托事件,因为当您对table排序时, .fixheadertable()会删除tr并再次将其附加到表中。 所以在排序后,这些tr被视为动态元素。


委托事件的.on()语法如下:

 $(container).on(eventName, target, handlerFunction)