Bootstrap 3 Modal Event (Hidden.Bs.Modal) Keeps Repeating

守給你的承諾、 提交于 2019-12-23 02:39:09

问题


I have 6 images that load in different 6 different modal windows and they each have a next button and also a close button in them. The next button works with the following jquery code:

    $('#nextModal12').click(function() {
        $('#featuresModal1').modal('hide');
        $('#featuresModal1').on('hidden.bs.modal', function () {
            $('#featuresModal2').modal('show');
            document.getElementById('#featuresModal1').style.display="none";
        });
    });

    $('#nextModal23').click(function() {
        $('#featuresModal2').modal('hide');     
        $('#featuresModal2').on('hidden.bs.modal', function () {
            $('#featuresModal3').modal('show');
            document.getElementById('#featuresModal2').style.display="none";                            
        });
    });     

However, the problem is: Even when I close/hide the first modal ('#nextModal12') by clicking the CLOSE button instead of the next, the second modal appears.

I believe this is because the hidden.bs.modal function is picked up and called again even when I'm not clicking the next button. How do I prevent the script from picking up the hidden.bs.modal function indiscriminately?


回答1:


Try use .one function instead of .on. When you use .on() your callback would be repeating again and again, beacuse you bind it again for each click;

$('#nextModal12').click(function() {
    $('#featuresModal1').modal('hide');
    $('#featuresModal1').one('hidden.bs.modal', function () {
        $('#featuresModal2').modal('show');
    });
});

$('#nextModal23').click(function() {
    $('#featuresModal2').modal('hide');     
    $('#featuresModal2').one('hidden.bs.modal', function () {
        $('#featuresModal3').modal('show');                          
    });
});



回答2:


Don't bind hidden.bs.modal again and again on modal click, just bind it once like,

$('#nextModal12').click(function() {
    $('#featuresModal1').modal('hide');
});
 $('#featuresModal1').on('hidden.bs.modal', function () {
    $('#featuresModal2').modal('show');
    $(this).hide();// you can use hide function
});

$('#nextModal23').click(function() {
    $('#featuresModal2').modal('hide');     
});   
$('#featuresModal2').on('hidden.bs.modal', function () {
    $('#featuresModal3').modal('show');
    $(this).hide(); 
});

Alternatively, you can try

$('#nextModal12').click(function() {
    $('#featuresModal1').modal('hide'); // hide first
    $('#featuresModal2').modal('show'); // show second
});

$('#nextModal23').click(function() {
    $('#featuresModal2').modal('hide');
    $('#featuresModal3').modal('show');
});


来源:https://stackoverflow.com/questions/27792795/bootstrap-3-modal-event-hidden-bs-modal-keeps-repeating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!