[英]jquery bootstrap modal closing after swal alert
我這里有這個代碼
單擊swal
后,我試圖關閉bootstrap
模式:
swal({
title:'',
text:'Thanks, we will contact you !',
type: 'success'
});
$("#modal").on('hidden.bs.modal', function () {
alert('boo');
$(this).data('bs.modal', null);
}).trigger();
什么都沒有發生,甚至沒有alert
,只有當我點擊模態上的關閉按鈕時,它才會顯示alert
並關閉。
您應該使用接受回調函數的.then()
方法,在該回調中您將關閉模態。
這里有一個演示來演示這將如何工作:
我不知道你的標記,所以,在我的例子中,我有一個按鈕來打開一個模態,當它被點擊時,一個
Sweet Alert
彈出窗口顯示包含兩個按鈕,如果按下那個彈出窗口的OK按鈕,模態將立即隱。模態的結構取自
BootStrap
的文檔。
var myModal = $('#exampleModal'); myModal.on('show.bs.modal', function() { swal({ title: 'Close modal ?', text: 'Do you want to close the modal ?', icon: 'warning', buttons: true }).then(function(value) { if(value === true) { myModal.modal('hide'); } }); });
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css" /> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> </div> <div class="modal-body"> <p class="alert alert-success">There are no any buttons to close the modal, it's closed either by pressing the backdrop or by pressing <strong>OK</strong> button of the Sweet Alert's popup.</p> </div> <div class="modal-footer"> normally, some buttons are placed here... </div> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.0/sweetalert.min.js"></script>
希望我能進一步推動你。
我發現這些問題的答案沒有工作,因為hide.bs.modal
返回從SWAL的承諾之前,甚至被觸發。 這是我的工作功能:
$('#myModal').on("hide.bs.modal", function (e) {
if (!$('#myModal').hasClass('programmatic')) {
e.preventDefault();
swal.fire({
title: 'Are you sure?',
text: "Please confirm that you want to cancel",
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Yes, cancel',
cancelButtonText: 'No, I clicked by mistake',
}).then(function(result) {
if (result.value) {
$('#myModal').addClass('programmatic');
$('#myModal').modal('hide');
e.stopPropagation();
} else {
e.stopPropagation();
}
});
}
return true;
});
$('#myModal').on('hidden.bs.modal', function () {
$('#myModal').removeClass('programmatic');
});
如您所見,每當代碼觸發關閉事件時,我都會向模態添加一個類,因此我使用e.preventDefault()
來防止模態關閉。 每當模式成功隱藏時,我都會再次刪除該類,以便下次用戶嘗試關閉它時它會再次工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.