简体   繁体   中英

Twtitter Bootstrap modal shown event firing multible times

I am assigning a click event to a button in a modal when the event shown has been fire:

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

My problem is that i have tabs in my modal, and when switching tabs the modal.shown event gets fired every time i click a tab, and thereby assiges another click event to the button each time. How do i prevent this from happening? Ofc. i can add an boolean to check if the events has been assigned, but it would be nice if i didnt have to :-)

Thanks in advance

You can use new version of bootstrap that has two events shown.bs.tab and shown.bs.modal or use following code to prevent several bindings

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

I don't know if it's good practice, but you can attach a variable to the modal-confirm element saying that you've assigned the click() event for it already:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM