简体   繁体   中英

Bootstrap modal via ajax and callbacks

I load content for modal by ajax like this:

$.ajax({
    url: 'p1.html',
      success: function(data){
        $(data).modal();
        alert('success')
        $('#myModal').on('show.bs.modal', function (e) {
            alert('why not work')
            set_valign_modal() // IMPORTANT - if You do not want to set content of modal boxes in middle in vertical, just remove this function init
        });

Quick question, why callback for modal:

$('#myModal').on('show.bs.modal', function (e){

doesn't work?

why callback for modal

I can think of three possible reasons:

  1. #myModal isn't the modal or an ancestor of it

  2. You don't hook the event until after it fires. The show.bs.modal event fires immediately when you show a modal. So if the modal shows immediately when you call $(data).modal(); , and you don't hook it until afterward, you've missed it.

  3. You never actually add the elements involved in the modal to the DOM

You are setting a listener on this line:

$('#myModal').on('show.bs.modal', function (e) {
            alert('why not work')
            set_valign_modal() // IMPORTANT - if You do not want to set content of modal boxes in middle in vertical, just remove this function init
        });

This should be set somewhere else, unless you intend to set the callback on the ajax response.

ALSO, this callback will be only called after firing:

$('#myModal').modal('show');

and since in your code you are calling the modal before, it will not fire the callback.

Try this instead:

$('#myModal').on('show.bs.modal', function (e) {
    alert('why not work');
});

$('#ajax').on('click',function()
{

    $.ajax({
      url: 'p1.html',
      success: function(data){
        $('#myModal').modal('show');

        }
    });
});

I should also say that it will only work in the case that data == '#myModal'

here is a working jsfiddle

    $(function() {

        $.ajax({
            url: 'p1.html',
              success: function(data){

               //## set instance of plugin in variable    
               var $m=$(data).modal(); 

               //and then add event using variable 
               $m.on('shown.bs.modal', function (e) {
                    alert('why not work')
                    set_valign_modal() // IMPORTANT - if You do not want to set content of modal boxes in middle in vertical, just remove this function init
                });
            }
        });
    })

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