gpt4 book ai didi

javascript - Bootstrap 模式事件 - 在返回之前等待回调完成

转载 作者:行者123 更新时间:2023-12-02 22:35:44 25 4
gpt4 key购买 nike

我知道这个问题听起来很幼稚,但想不出任何其他标题。

我正在使用 bootstrap modal 事件 hide.bs.modal 之一,该事件在模式消失之前被调用,以显示确认框。回调需要一个 bool 值。

$('#the-modal').on('hide.bs.modal', function () {
var self = this;

$.cofirm("are your sure you want to close", function() { // gets fired if confirmed
$(self).modal("hide"); // cannot do this,it will fire the event hide.bs.modal over and over.
});

return false; // obviously, this gets called first, but that's alright
}

此外,我没有使用传统的confirm,而是使用了 jquery 插件,它有自己的回调。

$(self).modal("hide"); 不能这样做,它会一遍又一遍地触发事件 hide.bs.modal

最佳答案

您需要一个标志来了解访问者是否确认。您可以这样做(使用元素的数据):

$('#myModal').on('hide.bs.modal', function() {
var thisModal = $(this);
var thisConfirmed = thisModal.data('confirmed');
if (!thisConfirmed) {
$.confirm({
title: 'Are you sure?',
content: '',
buttons: {
confirm: function() {
thisModal.data('confirmed', true);
thisModal.modal('hide');
},
cancel: function() {
/* Nothing here */
}
}
});
return false;
} else {
thisModal.data('confirmed', false);
return true;
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.js"></script>
<link href="http://cdnjs.cloudflare.com/ajax/libs/jquery-confirm/3.3.2/jquery-confirm.min.css" rel="stylesheet"/>
<script src="https://getbootstrap.com/docs/4.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Open modal</button>

<div class="modal fade" id="myModal" 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">New message</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="recipient-name" class="col-form-label">Recipient:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Message:</label>
<textarea class="form-control" id="message-text"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>

同时在 JSFiddle .

关于javascript - Bootstrap 模式事件 - 在返回之前等待回调完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58743989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com