与 jquery 和模态冲突的数据表

Datatables conflicting with jquery and modal

我在 bootstrap 应用程序中使用 jQuery DataTables。我们有多个 links,并针对它们设置了数据属性。当模式被切换时,数据被提取然后附加到模式。

问题是,如果我们在数据表中进行搜索,那么一旦 link 被点击,下面的代码就不会被调用。这可能是一个负载问题吗?知道如何解决吗?

$('.modal-toggle').click(function(e){
    // get control
    e.preventDefault();

    // get the vars from the data attributes
    modalType = $(this).data('modal-type').toLowerCase();
    modalTitle = $(this).data('modal-title');
    modalText = $(this).data('modal-text');

    // add appropriate footer
    if(modalType == "confirm"){
        modalUrl = $(this).data('modal-confirm-url');
        modalOptions = '<a href="' + modalUrl + '" class="btn btn-primary showhouse-colour white-text"><i class="icon-ok"></i> Yes</a><button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-ban-circle"></i> No</button>';
    }else if(modalType == "alert"){
        modalOptions = '<button class="btn btn-primary showhouse-colour" data-dismiss="modal" aria-hidden="true"><i class="icon-ok"></i> OK</button>';
    }else if(modalType == 'form-confirm'){
        modalOptions = '<button class="btn showhouse-colour white" data-dismiss="modal" id="confirm-form-yes"><i class="icon-ok"></i> Yes</button><button class="btn" data-dismiss="modal" aria-hidden="true"><i class="icon-ban-circle"></i> No</button>';
    }

    // set modal content
    $('.modal-title').html(modalTitle);
    $('.modal-text').html(modalText);
    $('.modal-footer').html(modalOptions);

    // if we have a confirm modalType
    $('#confirm-form-yes').click(function(){
        $('.confirm-form').submit();
    });
});

CAUSE

出于各种原因,DataTables 从 DOM 中删除了不可见的行,因此当您附加事件处理程序时,它仅适用于当前可见的元素。

SOLUTION

您需要通过在 on() 调用中提供选择器作为第二个参数来使用事件委托,请参见下面的示例,其中 example 是您的 table ID。

$(document).ready(function(){
    $('#example tbody').on('click', '.modal-toggle', function (e){
       // ... skipped ...
    });
});

来自jQueryon()方法文档:

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

参见 "Direct and delegated events" 中的 jQuery on() 方法文档和 jQuery DataTables – 为什么单击事件处理程序不起作用更多信息。