2014-03-05 90 views
0

现在,我的window.onbeforeunload过程是否正常工作,我不希望它火的时候,用户使用我所提供的按钮:我可以覆盖window.onbeforeunload吗?

<asp:Button ID="btnSaveResponses" runat="server" Text="Save" onclick="btnSaveResponses_Click" /> 
    <asp:Button ID="btnFinished" runat="server" Text="Finished" onclick="btnFinshed_Click" CausesValidation="False" /> 

如果用户点击其中任意一个,我不希望我的window.onbeforeunload程序启动。

这是一个过程:

<script language="javascript" type="text/javascript"> 
     window.onbeforeunload = function (e) { 
      var element1 = document.getElementById('btnFinished'); 
      if (element1 != null) { 
       //code to set the value variable. 
       document.getElementById('btnFinished').click(); 
      } 
      else { 
       alert("element is null"); 
      } 
      return false; 
     }; 
</script> 

我加入这两个函数到页面的底部:

<script language="javascript" type="text/javascript"> 
     function setDoNotFire 
     { 
      var doNotFire=true; 
     }; 
</script> 
<script language="javascript" type="text/javascript"> 
     function Fire 
     { 
      var doNotFire=false; 
     }; 
</script> 

加上这样的:

<body onload ="Fire()"> 

这:

<asp:Button ID="btnSaveResponses" runat="server" Text="Save" onclick="btnSaveResponses_Click" OnClientClick ="setDoNotFire()"/> 
    <asp:Button ID="btnFinished" runat="server" Text="Finished" onclick="btnFinshed_Click" CausesValidation="False" OnClientClick ="setDoNotFire()"/> 

最后:

<script language="javascript" type="text/javascript"> 
     window.onbeforeunload = function (e) { 
      if (doNotFire!=true) { 
       var element1 = document.getElementById('btnFinished'); 
       if (element1 != null) { 
        //code to set the value variable. 
        document.getElementById('btnFinished').click(); 
       } 
       else { 
        alert("element is null"); 
       } 
       return false; 
      } 
     }; 
</script> 

它没有在所有的工作。它不再做任何事情,所以我猜测它找不到变量doNotFire。

+0

有什么问题? –

+0

我不想看到“此页面要求您确认您要离开 - 您输入的数据可能无法保存。”当正确的按钮被点击时,只有当选项卡或窗口关闭时。 –

回答

0

没有必要重写它,只是使现有的更灵活。 声明一个全局变量doNotFire =false。 单击按钮时,swith变为true。 在你的onBeforeUnload的代码中,检查doNotFire是否为false。

<html> 
<head> 
<script type="text/javascript"> 
doNotFire = false; 
function doSomething(){ 
if (!doNotFire){ 
.... 
} 
</script> 
</head> 
<body onbeforeunload="doSomething();"> 
... 
<asp:Button ID="btnSaveResponses" runat="server" Text="Save" onclick="doNotFiretrue;btnSaveResponses_Click();" /> 
    <asp:Button ID="btnFinished" runat="server" Text="Finished" onclick="doNotFiretrue; btnFinshed_Click();" CausesValidation="False" /> 

</body> 
</html> 
+0

我不认为这有效。我将这两个函数添加到页面底部:

+0

会在一分钟内给你写一个代码示例。让我从平板电脑切换到电脑... –

+0

看起来不错,但不会工作。首先,onbeforeunload不是body的有效属性。 –

相关问题