javascript - 就绪函数内的委托(delegate)函数

标签 javascript jquery delegation

我正在使用带有隐藏行的 DataTables 插件,当使用分页时,我的点击事件失败,没有控制台错误。

这是函数:

$(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' );
    }
});

});

正如您所看到的,我正在使用委托(delegate),但该函数被包装在一个准备好的函数中。我确信这就是问题所在。我该如何解决这个问题?

上述问题是错误提出的,请参阅答案下我的评论。

最佳答案

阅读.on()

由于元素是动态添加的,因此您无法将事件直接绑定(bind)到它们。因此您必须使用 Event Delegation .

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

语法

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

下面的代码不是事件委托(delegate)

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

关于javascript - 就绪函数内的委托(delegate)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19609085/

相关文章:

javascript - 事件监听器悬停更改其他元素

javascript - 如何使用 JavaScript/JQuery 获取 Gridview 中的复选框选中值

jquery - 为什么 jquery 无法在我的本地计算机上运行?

ios - 使用委托(delegate)清理数组

c++ - 使用 Qt 在 C++ 中委派类构造函数

javascript - 如何在 javascript 中添加 html <br> 标签

javascript - 将 JSON 对象写入现有的 .json 文件

javascript - MooTools 拖动/ slider 无法正常运行

jquery - Rails jquery ui 日期选择器

ios - 呈现新 View Controller 时销毁以前的 View Controller