2012-09-17 45 views
1

我已經寫了下面的代碼在卸載中運行onbeforeunload。但是,這似乎並不奏效。有沒有人知道我的代碼有什麼問題,無論如何,使它的工作?onbeforeunload不能在卸載內工作

$(window).unload(function() { 
    if ($('.submitAction').val() == "" && isChange) { 
     window.onbeforeunload = confirmExit; 
    } 
}); 

function confirmExit() { 
    return "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?"; 
} 

回答

5

onunload事件是absolute last event當用戶導航離開頁面或關閉瀏覽器觸發。

結合onbeforeunload事件onunload事件是毫無意義的,因爲這事件已經發生(因此得名onbeforeunload)。該解決方案將綁定到onbeforeunload事件,然後事件實際發生,例如加載頁面時。

像這樣(未經):

$(window).bind('beforeunload', function() { 
    if ($('.submitAction').val() == "" && isChange) { 
     return "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

此行返回一個字符串:

return "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?"; 

我想你的意思是:

return window.confirm("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

的'beforeunload'事件實際上讓你返回一個字符串,這是用來很好地提示用戶(或惹惱他們購買偉哥).. –

+0

@MikeChristensen - 我會的。好吧,我今天學到了一些新東西。 –