<a href="https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h" id="leave">click here to leave the page</a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Changes made may not be saved.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
$("#leave").click(function() {
$(window).bind('beforeunload', function() {
return 'Changes you made may not be Saved';
});
});
答案 0 :(得分:1)
您可以阻止leave
链接的默认行为,显示对话框并使用超时在几秒钟内重定向页面。
示例:
$("#leave").click(function(e) {
e.preventDefault();
var link = this.href;
//code to show dialog
window.setTimeout(function() {
window.location.href = link;
}, 2000);
});
此外,您需要将脚本代码包装在script
html标记中。
答案 1 :(得分:0)
为什么不能在模式按钮内设置重定向逻辑,并让a
元素显示模式。这似乎是一个更简单的解决方案。
$("#leave").click(e => {
e.preventDefault()
$("#myModal").modal({
show: true
})
})
$("#procceedLeaveBtn").click(() => {
window.location.href = "https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h"
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<a href="#" id="leave">click here to leave the page</a>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Changes made may not be saved.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button id="procceedLeaveBtn" type="button" class="btn btn-default" data-dismiss="modal">Procceed</button>
</div>
</div>
</div>
</div>
data-href
属性,然后在click handler中检索它。这取决于您。