javascript - 在 Bootstrap 中触发模态隐藏时是否可以停止模态隐藏?
问题描述
在引导程序中,当点击关闭按钮或背景时,是否可以停止模态隐藏?
例如,如果我运行一个语句来检查真假。如果为假,我可以停止模态隐藏吗?
$(document).on('hide.bs.modal', '#test-modal', function(e) {
var confirm = confirm("Sure you wanna close this modal?");
if (confirm == true) {
// i'm sure, continue closing the modal
} else {
// halt closing this modal
}
});
这里有一个小提琴准备测试......
解决方案
您可以简单地使用e.preventDefault
inhide.bs.modal
来防止模式关闭。另外,请注意这confirm
是一个窗口对象,因此您可能应该选择不同的变量名称以避免这种情况。
请参阅概念验证示例:
$('#test-modal').modal('show');
$(document).on('hide.bs.modal', '#test-modal', function(e) {
var shouldCloseModal = confirm("Sure you wanna close this modal?");
if (!shouldCloseModal) {
e.preventDefault();
}
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<div class="modal fade" id="test-modal" tabindex="-1">
<div class="modal-dialog">
<form class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Test Modal</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Try close me and then stop me! If you can...
</div>
</form>
</div>
</div>
推荐阅读
- javascript - iframe下处理#document的方法
- java - 使用 Stripe 支付时如何正确设置金额?
- python - Python 在列表中替换
- python - tkinter 过去的文字保持字体
- excel - 将多个单元格从excel列复制到剪贴板
- php - 当 enable_query_strings 设置为 true 时,Codeigniter 导航进入默认控制器
- python - 将数据从一个表映射到另一个表?
- javascript - Knex 和 SQL 数据库的引号问题
- javascript - 如何做响应式路径
- sql - MATERIALIZED VIEW 中的最大行数