2014-03-05 132 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的有效屬性。 –

相關問題