我想在离开页面之前显示模式弹出窗口

时间:2018-08-29 04:09:42

标签: javascript jquery html css model-view-controller

<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">&times;</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';
  });
});

here is the js fiddle am working on

2 个答案:

答案 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">&times;</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>
您甚至可以在button元素内指定data-href属性,然后在click handler中检索它。这取决于您。