我可以覆盖window.onbeforeunload吗?

时间:2014-03-05 13:17:36

标签: javascript

既然我的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。

1 个答案:

答案 0 :(得分:0)

无需覆盖它,只需使现有的更灵活。 声明一个全局变量doNotFire =false。 单击按钮时,swith变量为true。 在onBeforeUnload代码中,检查doNotFire是否为假。

<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>