2016-11-28 105 views
-1

我試圖在用戶轉到應用內的其他頁面之前提醒用戶,如果有未保存的信息。我遵循several stackoverflows的建議,使用.beforeunload ,但它只在刷新頁面時才起作用,而不是在點擊指向站點上另一頁的鏈接時。我誤解如何使用beforeunload或我需要另一個事件監聽器?.beforeunload只處理刷新

的application.js

//= require forms.js 

forms.js

$(window).on('beforeunload', function() { 
    console.log('unloading') 
}); 
+0

當您點擊鏈接轉到其他網站/頁面時,它應該會啓動。 – epascarello

+0

@epascarello當您轉到網站上的其他頁面時,它不會。任何想法爲什麼? – gwalshington

+0

所以你有它,所以你保存日誌頁面導航時發生?我們在這裏處理什麼瀏覽器? – epascarello

回答

0

beforeunload事件是這樣的:

// Fires just before leaving/refreshing the page. Handler will 
    // be passed the event object and if a returnValue is set on the 
    // event, the browser will display a confirmation dialog with the 
    // returnValue message displayed. 
    window.addEventListener("beforeunload", function (evt) { 
     evt.returnValue = "Setting this to anything but an empty string, causes this to work!"; 
    }, false); 

爲例見this Fiddle

+0

那麼OPs代碼有什麼問題? – epascarello

+0

@epascarello她沒有在事件對象上設置'returnValue'。正如我的評論所表明的。 –

+0

它應該正常工作的方式OP,它可以在沒有returnValue的情況下觸發內部的東西。 – epascarello