【问题标题】:Why 'click' event not triggering for buttons added dynamically to a table?为什么“点击”事件不会触发动态添加到表格的按钮?
【发布时间】:2020-03-02 02:21:16
【问题描述】:

我将DataTable 用于通过Ajax 调用填充的表。有些列是来自数据库的数据,但在最后一列中我放了一些按钮。当我点击那个按钮时,click 事件没有被触发,为什么?

我尝试委托该事件,但它仅在第一次触发(我点击的第一个按钮,后续点击没有):

$( '#my_table' ).DataTable( {
            language: {
                url: 'https://cdn.datatables.net/plug-ins/1.10.20/i18n/Italian.json'
            },
            ajax: {
                url: ccwhatsapp_ajax.url + '?action=get_users_for_datatable'
            },
            responsive: true,
            dom: 'Bfrtip',
            columns: [
                { data: 'full_name' },
                { data: 'login_email' },
                { data: 'phone' },
                { data: 'info' },
                { data: 'actions' }
            ],
            columnDefs: [
                { width: '20%', targets: [0, 1, 2, 3] },
            ]
        } );

$( '#my_table' ).on( 'click', 'tbody tr td button.btn', function () {
                console.log("Click on a button!");
            } );

            $( "#my_table" ).delegate( "tbody tr td button.btn", "click", function() {
                console.log("Click on a button!");
            });

            $( '.btn-primary' ).on( 'click', function () {
                console.log("Click on a button!");
            } );

怎么了?

【问题讨论】:

  • 对于动态创建的按钮,您应该使用 $(document).on("click", "#my_table" ...
  • 只要您不破坏要附加事件处理程序的根元素,它就应该可以工作。根不必是document,但最好附加到表的上级。使用开发者控制台检查您使用的选择器是否真的选择了元素。

标签: javascript jquery events delegates click


【解决方案1】:

尝试将监听器更改为:

$( '#my_table tbody' ).on( 'click', 'tr td button.btn', function () {
            console.log("Click on a button!");
} );

DataTables 网站here 上有一个例子。

【讨论】:

    【解决方案2】:

    我使用表格的div“祖先/上升”解决了:

    $( '#table_container table' ).on( 'click', 'button.btn', function () {
        console.log($(this));
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-09
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多