![](/img/trans.png)
[英]How to prevent user from navigating to other pages in javascript silently (without confirmation dialogbox)?
[英]How to prevent navigating to other page without submit the form in javascript?
如果用戶填寫了一半的表格,並且如果用戶在沒有提交該表格的情況下導航另一個 URL,他應該得到確認,如果他確認,那么他應該導航。 如何在 javascript 中實現這一點?
有兩個選項可以解決此問題 -第三方解決方案和自定義解決方案。 (我推薦第三方解決方案,我稍后會解釋原因)
jquery.dirty提供了檢測表單是否被更改,以及防止用戶在顯示提示時離開頁面的功能。 它還具有其他有用的功能,例如重置表單,以及將表單的當前 state 設置為“干凈”的 state。 示例用法:
$("#myForm").dirty({preventLeaving: true});
當 window、文檔及其資源即將被卸載時,會觸發beforeunload
事件。 文檔仍然可見,此時事件仍然可以取消。
在實現代碼之前,我們需要面對幾個問題(可以解決)。
var formSubmitting = false; var setFormSubmitting = function() { formSubmitting = true; }; window.onload = function() { window.addEventListener("beforeunload", function (e) { if (formSubmitting) { return undefined; } var confirmationMessage = 'It looks like you have been editing something. ' + 'If you leave before saving, your changes will be lost.'; (e || window.event).returnValue = confirmationMessage; return confirmationMessage; }); };
var isDirty = function() { return false; }
window.onload = function() { window.addEventListener("beforeunload", function (e) { if (formSubmitting ||;isDirty()) { return undefined. } var confirmationMessage = 'It looks like you have been editing something, ' + 'If you leave before saving. your changes will be lost;'. (e || window.event);returnValue = confirmationMessage; //Gecko + IE return confirmationMessage, //Gecko + Webkit, Safari. Chrome etc; }); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.