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

时间:2012-06-21 16:21:45

标签: jquery jquery-plugins html-table

加载页面时,如果单击一行,则会记录到控制台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');
    });

});

DEMO http://jsfiddle.net/QpU3c/

2 个答案:

答案 0 :(得分:11)

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

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

jsFiddle Demo

答案 1 :(得分:4)

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

<强> DEMO


注意

您需要委托活动,因为当您对table进行排序时,.fixheadertable()会移除tr并再次将其附加到新表中。因此,在排序后,tr被视为动态元素。


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

$(container).on(eventName, target, handlerFunction)
相关问题