繁体   English   中英

刷新页面时打开BS Modal,询问用户是否确定

[英]Open BS Modal when refreshing page and ask if the user is sure

当用户尝试刷新或离开页面时,如何打开Bootstrap模式? 模态应显示为:““确定要离开此页面吗?

我遵循以下代码:

 window.onbeforeunload = function() { $('#myModal').modal("show"); return "Data will be lost if you leave the page, are you sure?"; }; 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to navigate away from this page? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No I want to stay</button> <button type="button" class="btn btn-primary">Yes, I'm sure</button> </div> </div> </div> </div> 

但是,使用此代码段将打开模式,但页面仍会刷新。

当用户尝试离开时,将触发unload事件。 但是,如果将DIV用作弹出窗口,则浏览器将在用户有机会阅读它之前导航离开。 为了使它们保持在那里,您必须使用警报/提示/确认对话框。

对我来说,绑定到html效果很好,而不是卸载。

完整参考: https : //stackoverflow.com/a/30603477/1081909

 $("html").bind("mouseleave", function () { $('#myModal').modal("show"); $("#okButton").click(function(){ location.reload(); }); //$("html").unbind("mouseleave"); }); 
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to navigate away from this page? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No I want to stay</button> <button id="okButton" type="button" class="btn btn-primary">Yes, I'm sure</button> </div> </div> </div> </div> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM