Twtitter Bootstrap模式显示事件多次触发

Twtitter Bootstrap modal shown event firing multible times

本文关键字:事件 Bootstrap 模式 显示 Twtitter      更新时间:2024-02-18

当显示的事件被激发时,我正在将点击事件分配给模式中的按钮:

modal.on('shown', function(){
    modal.on('click', '.modal-confirm', function(e){
        ...
    });
});

我的问题是,我的模式中有选项卡,当切换选项卡时,每次单击选项卡都会触发modal.show事件,从而每次都会为按钮分配另一个单击事件。我该如何防止这种情况发生?Ofc。我可以添加一个布尔值来检查事件是否已经分配,但如果我不必这样做,那就太好了:-)

提前感谢

您可以使用具有两个事件shown.bs.tabshown.bs.modal的引导程序的新版本,或者使用以下代码来阻止多个绑定

modal.off('shown').on('shown', function(){
    modal.off('click').on('click', '.modal-confirm', function(e){
        ...
    });
});

我不知道这是否是一个好的做法,但你可以在模态确认元素上附加一个变量,表示你已经为它分配了click()事件:

modal.on('shown', function(){
    if ($(this).find('.modal-confirm').data('hasEvent') != null) {
        modal.on('click', '.modal-confirm', function(e){
            ...
        });
    }
});