这段代码(来自我正在开发的wordpress插件)似乎有用 - 打开一个模态,进行ajax调用,检索一些数据并在模态中显示它,使用Bootstrap 3和(native WP)jQuery 1.11
我感到困惑的是,为什么模态在没有调用$('#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">×</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 admin ajax并调用实际的uri,数据指向函数。)
答案 0 :(得分:2)
这是因为a
元素中的属性会使您的模态在点击时打开。
data-toggle="modal"
data-target="#registrantModal"
相当于$(element).modal('show')
。
请参阅文档here
中的实例