【问题标题】:jQuery click() event isn't fired after sorting table排序表后不触发 jQuery click() 事件
【发布时间】:2017-07-29 18:37:05
【问题描述】:

当你加载页面时,如果你点击一行,它会记录到控制台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/

【问题讨论】:

  • 链接很好,但请务必在问题本身中发布相关代码和标记meta.stackexchange.com/questions/118392/…
  • @T.J.Crowder 谢谢,我添加了没有被触发的事件:)
  • @T.J.Crowder 我不得不使用 jsfiddle 因为它使用了一些外部资源 (css/js)
  • @T.J.Crowder 我正在添加代码,但 thecodeparadox 比我快。再次感谢,一直在学习!

标签: jquery jquery-plugins html-table


【解决方案1】:

你应该使用event delegation,因为插件改变了原来的tr元素,所以他们失去了附加的事件处理程序。处理程序应该附加在表本身上,因为它肯定不会改变。

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

jsFiddle Demo

【讨论】:

  • 太棒了,谢谢!它解决了排序和分页的问题。
  • @kapa 如果我能拥抱你,我会的。
  • @BernieDavies 这让我很开心,让我们假装它发生了:)
【解决方案2】:
$("table.ex").on('click', 'tr', function(){
    console.log('clicked');
});

DEMO


注意

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


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

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

【讨论】: