jQuery click() event isn't fired after sorting table

烈酒焚心 提交于 2019-12-22 09:08:05

问题


When you load the page, if you click on a line, it logs to the console clicked.

But, if you sort the table (click on the table header), click event on tr doesn't get fired if you try to click on the rows.

I'm using this plugin: 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/


回答1:


You should use event delegation, because the plugin changes the original tr elements, so they lose their attached event handlers. The handler should be attached on the table itself, because it is certainly not changing.

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

jsFiddle Demo




回答2:


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

DEMO


Note

You need delegate event, because when you're sorting the table, .fixheadertable() removes the trs and again append it to table newly. So after sorting those trs are treated as dynamic element.


Syntax of .on() for delegate event is like:

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


来源:https://stackoverflow.com/questions/11142500/jquery-click-event-isnt-fired-after-sorting-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!