2016-08-05 22 views
0

我試圖檢測用戶何時離開頁面。我認爲.on(「unload」,fn)方法應該這樣做:jQuery .on(「unload」,fn)不適合我

$(document).ready(function(){ 
    $(window).on("unload", function(){ 
    alert("Goodbye!"); 
    }); 
}); 

但它似乎沒有工作。當我離開頁面時沒有任何反應。但是,如果將「卸載」更改爲「加載」,則警告框會在頁面加載時適當地顯示。

這是正確的方式去做我想要的嗎?

回答

1

可能:

<script language="JavaScript"> 
    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?"; 
    } 
</script> 

http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm

「beforeunload」 採取的措施將是一個事件比 「卸載」 之一,它似乎跟棄用更可靠。我也讀了「beforeunload」事件是更可靠的從JavaScript稱爲比jQuery的

所以你的情況時:

$(document).ready(function(){ 
     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?"; 
     } 
}); 
+0

的現場演示的作品,但jQuery的似乎不知道「onbeforeunload」方法。 :( –

+0

你可以在javascript函數中編寫jQuery代碼(被小心)。用另一種方式來說,只需在javascript中添加這個事件,並在旁邊做一些常用的jQuery代碼。 – technico

+0

添加代碼以適合你的案例。 – technico