Jquery Show Popup only when window is closed

烈酒焚心 提交于 2019-12-13 04:59:55

问题


I am trying to display a confirmation message when the user closes the browser/tab and not when any of the links on page is clicked.

I have got the first part of displaying the message on window close working nicely but problem is that the message/alert is displayed also when user clicks on any link on the page.

I have got code from somewhere to prevent this behavior but still when ever any link is clicked the alert pops up.

Here is the code:

<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>                         
<script type="text/javascript" src="js/backfix-min.js"></script>

$(document).ready(function() {
    $(window).bind('beforeunload', function(e){
            $("#lead-gen-modal").dialog("open");
            // This line only appears in alert boxes for IE
            return "Wait\! Don\'t Go\! We have a special offer for you\. Stay on this page to receive big savings\!";   
    }); 

    $("a").click(function() {
        window.onbeforeunload=null;
    });         
});

回答1:


just use a global variable and set it to false when clicking a link.

var key = true;
$(window).bind('beforeunload', function(e){
  if(key)
  $("#lead-gen-modal").dialog("open");
}); 

update :

 $(document).on("click","a",function() {
      key=false; 
 }); 

or if you just want to prevent closing window you can do this :

window.onbeforeunload = function(e){
   if(key)
   return false;
}



回答2:


I think you are looking for something like this.

$(window).unload(function() {
  alert("bye");
});

If that does not work on Chrome try this

$(window).on('beforeunload', function() {
  return "bye";
});

jQuery API: unload() http://api.jquery.com/unload/



来源:https://stackoverflow.com/questions/26484767/jquery-show-popup-only-when-window-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!