如何在JS中停止页面卸载(导航)?

有谁知道如何阻止页面重新加载或导航?

  jQuery(function($){

     / *全球卸载通知* /
     warning = true;

    如果(警告){
         $(window).bind(“unload”,function(){ 
            如果(确认(“你想离开这个页面”)== true){
                 //他们按下确定
                警报( 'OK');
             } else {
                 //他们按下取消
                警报( '取消');
                返回false;
             }
         });
     }
 }); 

我目前正在电子商务网站上工作,显示未来订单的页面可以使用+/-button更改已订购商品的数量。 以这种方式改变数量实际上并不改变订单本身,他们必须按下确认,并因此做出积极的行动来改变订单。

但是,如果他们已经改变了数量并离开页面,我想警告他们,如果这是偶然事件,他们会这样做,因为如果浏览或刷新页面,更改的数量将会丢失。

在上面的代码中,我使用了一个默认为false的全局variables(它只对testing是真的),当数量发生变化时,我将更新这个variables为true,当他们确认更改时,我将它设置为false 。

如果警告是真的,页面卸载,我给他们一个确认框,如果他们说不,他们想留在这个页面,我需要停止卸载。 返回false不起作用,它仍然允许用户导航(警报在那里仅用于debugging)

有任何想法吗?

onbeforeunload是你想要的; 你的函数“应该为Event对象的returnValue属性赋值一个string值并返回相同的string” 。 有关详细信息,请查看Microsoft和Mozilla的文档。

您返回的string将被浏览器用来显示用户自定义确认框,允许他们拒绝留在那里,如果他们select。 必须这样做才能防止恶意脚本导致拒绝浏览器攻击。

此代码根据娜塔莉的build议发出警告,但如果页面上的表单被提交,则禁用该警告。 使用JQuery。

 var warning = true; window.onbeforeunload = function() { if (warning) { return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes"; } } $('form').submit(function() { window.onbeforeunload = null; }); 

你想使用onbeforeunload事件。

 window.onbeforeunload = function() { if (warning) { return 'You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will loose your unsaved changes'; } } 

不支持在铬,狩猎和歌剧

 window.onbeforeunload = confirmExit; function confirmExit() { return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?"; } 

尝试使用e.preventDefault()而不是返回false。 'e'将是您的卸载callback的第一个参数。