javascript 如何防止使用 jQuery 卸载页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9564663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 07:03:56  来源:igfitidea点击:

How can I prevent a page unload with jQuery?

javascriptjqueryjquery-events

提问by tatiana_c

In my program, if a user tries to leave a page, he'll receive a dialog box asking if he is sure he wants to leave.

在我的程序中,如果用户试图离开一个页面,他会收到一个对话框,询问他是否确定要离开。

How should I implement the 'cancel' option if the user chooses not to leave the page?

如果用户选择不离开页面,我应该如何实现“取消”选项?

Source javascript code:

源代码:

$(window).unload(function(){
   var c= confirm ("Are you sure?");
   if (c){
       alert("Thanks. Good luck!");
   }
   else{
       ????
   }
});

回答by sandeep

window.onbeforeunload = function() {
    return 'You have unsaved changes!';
}

many question about this in stackoverflow How can I override the OnBeforeUnload dialog and replace it with my own?

stackoverflow 中很多关于此的问题 如何覆盖 OnBeforeUnload 对话框并将其替换为我自己的?

JavaScript + onbeforeunload

JavaScript + onbeforeunload

回答by user3134411

 jQuery(window).on('beforeunload',function(){
    var value = navigateAway(isDirty);
    if(value=="changed")`enter code here`
    {
        if(jQuery("#saveCheck").val()=="false")
        {
            return "<?php echo JText::_('OVR_WANT_TO_LEAVE');?>";
        }
    }

 });