2015-11-11 2 views
0

Этот код (из плагина wordpress, который я разрабатываю), кажется, работает - открытие модального кода, создание ajax-вызова, извлечение некоторых данных и их отображение в модальном режиме с использованием Bootstrap 3 и (родной WP) jQuery 1.11.Обновление Bootstrap Modal Via Ajax - почему модальный ('show') нужен здесь?

Что меня смущает, почему модальный открытый без звонка $('#registrantModal').modal('show');?

$(document).ready(function($) { 
    $('.get_registrants').click(function(){ 
     $(this).removeData('bs.modal'); 
     classDescription = $(this).attr("data-classDescription"); 
     className = $(this).attr("data-className"); 
     $('#registrantModal').find('#ClassTitle')[0].innerHTML = className; 
     $('#registrantModal').find('#ClasseRegistrants')[0].innerHTML = '<i class="fa fa-spinner fa-3x fa-spin"></i>'; 
     var htmlClassDescription = '<div class="modal_class_description">'; 
     htmlClassDescription += decodeURIComponent(classDescription) + '</div>'; 
     htmlClassDescription += '<h5 class="mz_registrants_header">Registrants</h5>'; 
     $('#registrantModal').find('#class-description-modal-body')[0].innerHTML = htmlClassDescription; 
     var ajaxFn = function() { 
      $.ajax({ 
       type: "GET", 
       dataType: 'json', 
       url: '/api/registrant/'+$(this).data('className'), 
       error: function(data) { 
            fakeResponse = {"message":"Student of a Class", "type":"success"} 
        if(fakeResponse.type == "success") { 
          htmlRegistrants = '<ul class="class_registrants">'; 
          htmlRegistrants += '<li>' + fakeResponse.message + '</li>'; 
          htmlRegistrants += '</ul>'; 
          $('#registrantModal').find('#ClasseRegistrants')[0].innerHTML = htmlRegistrants; 
        }else{ 
          $('#registrantModal').find('#class-description-modal-body')[0].innerHTML = "error!"; 
        } 
       } // ./ Ajax Success 
      }); // ./Ajax 
     } // ./ajaxFn 
     setTimeout(ajaxFn, 1000); 
    }); // ./Click 
}); 

Вот HTML:

<a class="modal-toggle get_registrants btn" data-toggle="modal" data-target="#registrantModal" data-classDescription="Some Details about this event" data-className="Student of a Class" data-classID="12345" href="#">An Event</a> 

<div class="modal fade" id="registrantModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
       <h4 class="modal-title ' . $className .'" id="ClassTitle"></h4> 
      </div> 
      <div class="modal-body" id="class-description-modal-body"></div> 
      <div class="modal-body" id="ClasseRegistrants"></div> 
      <div class="modal-footer"> 
      </div> 
     </div> 
    </div> 
</div> 

И fiddle.

(В реальном коде я использую WordPress админ Аякс и вызов фактической Ури и точки данных для функции.)

ответ

2

Это происходит потому, что ваши атрибуты в a элементе делает ваш модальный открытыми по щелчку.

data-toggle="modal"

data-target="#registrantModal"

Это эквивалентно $(element).modal('show').

См. Живой пример в документации here

+0

сладкий! я вижу, что я могу «переключать» 'data-toggle =" modal "' в HTML и '$ ('# registrantModal'). modal ('show');' в js с тем же результатом. любой вопрос, почему в этом случае он может быть более уместным, чем другой? – MikeiLL

+1

В вашем случае это не важно, но иногда вы хотите показать модальное не событие click. – makshh

Смежные вопросы