就绪函数中的委派函数

Delegated function inside ready function

本文关键字:函数 委派 就绪      更新时间:2023-09-26

我正在使用带有隐藏行的数据表插件,使用分页时,我的单击事件失败而没有控制台错误。

这是函数:

$(document).ready(function() {
$('#datatable tbody td a').on('click', function (e) {
    e.preventDefault();
    var nTr = $(this).parents('tr')[0];
    if ( oTable.fnIsOpen(nTr) ) {
        /* This row is already open - close it */
        $(this).addClass('glyphicon-arrow-down');
        $(this).removeClass('glyphicon-arrow-up');
        oTable.fnClose( nTr );
    } else {
        /* Open this row */
        $(this).addClass('glyphicon-arrow-up');
        $(this).removeClass('glyphicon-arrow-down');
        oTable.fnOpen( nTr, fnFormatDetails(oTable, nTr), 'details' );
    }
});
});

如您所见,我正在使用委派,但该函数包装在一个就绪函数中。我确定这就是问题所在。我该如何解决这个问题?

上述问题被错误地问了,请参阅我在答案下的评论。

Read .on()

由于元素是动态添加的,因此您无法将事件直接绑定到它们。因此,您必须使用事件委派。

$('#datatable').on('click', 'tbody td a', function (e) {});

语法

$( elements ).on( events, selector, data, handler );

下面的代码不Event Delegation

$('#datatable tbody td a').on('click', function (e) {