[英]Bootstrap modal via ajax and callbacks
I load content for modal by ajax like this: 我像这样通过ajax加载模式内容:
$.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: 我可以想到三个可能的原因:
#myModal
isn't the modal or an ancestor of it #myModal
不是模态或它的祖先
You don't hook the event until after it fires. 在事件触发之前,您不要钩住事件。 The
show.bs.modal
event fires immediately when you show a modal. 显示模态时,将立即触发
show.bs.modal
事件。 So if the modal shows immediately when you call $(data).modal();
因此,如果在调用
$(data).modal();
时立即显示模态$(data).modal();
, and you don't hook it until afterward, you've missed it. ,直到您之后再钩上它,您才错过了它。
You never actually add the elements involved in the modal to the DOM 您从未真正将模式中涉及的元素添加到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. 除非您打算在ajax响应上设置回调,否则应该在其他地方设置它。
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' 我还应该说,它仅在data =='#myModal'的情况下有效
$(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
});
}
});
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.