[英]Bootstrap Modal won't close, previously appended to Body using JQuery
So I go to all this trouble to get the modal appended to the body and the text box working then I go to close it on the AJAX success event but nothing I try seems to work.所以我遇到了所有这些麻烦,将模态附加到正文和文本框,然后我在 AJAX 成功事件上关闭它,但我尝试的任何内容似乎都不起作用。
var id;
var refundAmount = '';
var token = $("meta[name='csrf-token']").attr('content');
$('[data-toggle="modal"]').on('click', function(e) {
var checkeventcount = 1;
var prevTarget;
// Find the id from the modals href attribute
id = $(this).attr('href').replace(/[^0-9.]/g, "");
$('#new_refund_modal' + id).on('show.bs.modal', function (e) {
if(typeof prevTarget == 'undefined' || (checkeventcount==1 && e.target!=prevTarget))
{
prevTarget = e.target;
checkeventcount++;
e.preventDefault();
$(e.target).appendTo('body').modal('show');
$(document.body).delegate('#new_refund_input' + id, 'change keyup paste mouseup', function() {
if ($(this).val() != refundAmount) {
refundAmount = $(this).val();
}
});
}
else if(e.target==prevTarget && checkeventcount==2)
{
checkeventcount--;
}
});
});
$('.refund-submit-btn').click(function (e) {
e.preventDefault();
$.ajax({
url: '<%= payment_plan_refund_url %>',
type: 'post',
data: { authenticity_token: token, id: id, payment: { refund_amount: refundAmount }},
success: function (data, status) {
$('#new_refund_modal' + id).modal('hide');
}
});
});
Here's a list of the different fixes I have tried, The close button in the modal still works so I have been trying to trigger that on the AJAX Success but that fix doesn't seem to work either这是我尝试过的不同修复程序的列表,模式中的关闭按钮仍然有效,所以我一直试图在 AJAX Success 上触发它,但该修复程序似乎也不起作用
1) $('#new_refund_modal' + id).modal('hide');
2) $('#new_refund_modal' + id).data('modal', null);
3) $('#new_refund_modal' + id).remove();
$('.modal-backdrop').remove();
$('body').removeClass('modal-open');
4) $('#closeModal' + id).click();
All previously registered event handlers are gone when you removed/re-added the elements.当您删除/重新添加元素时,所有以前注册的事件处理程序都消失了。 Also newly created DOM element will not have the handlers automatically registered
新创建的 DOM 元素也不会自动注册处理程序
For example assuming this is your DOM tree:例如,假设这是您的 DOM 树:
body
+-- modal1
+-- close-button
If you register the handler on close-button, when modal1 is removed/re-added from the DOM the handlers are gone.如果您在关闭按钮上注册处理程序,当从 DOM 中删除/重新添加 modal1 时,处理程序就消失了。 This also applies if the handlers are added before modal1 is created and attached to DOM
如果在创建 modal1 并附加到 DOM之前添加处理程序,这也适用
You can either re-register the handlers when you remove/re-add the DOM element, or register the handler on the ancester elements (because elements triggered down the tree will propagate upwards).您可以在删除/重新添加 DOM 元素时重新注册处理程序,也可以在祖先元素上注册处理程序(因为向下触发的元素将向上传播)。
For example, instead of例如,代替
$('#modal1 .close-button').click(function() { .. })
Use:用:
$('body').on('click', '#modal1 .close-button', function() { .. });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.