我已经使用这些页面上描述的技术实现了“未保存的更改”警告:
用于“未保存数据”保护的客户端/JS 框架? https://stackoverflow.com/questions/140460
http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
除了页面上的 DropDownList 之外,此方法效果很好。它有一个自动回发功能,我想要onbeforeunload
触发,因为未保存的更改将会丢失,但它不起作用。是否应该提高onbeforeunload
事件?我能以某种方式让它引发事件吗?
Edit:
DropDownList 位于 UpdatePanel 内部,因此这意味着它不会卸载页面,这就是原因onbeforeunload
没有被触发。有什么方法可以以编程方式触发该事件吗?或者我是否必须滚动自己的模仿确认对话框?
Edit2
我现在有了一个解决方案,可以将对话框添加到 UpdatePanel 的异步回发中。我编辑了原始脚本,添加了对setConfirmAsyncPostBack()
正如我的解决方案中所述。
这是我的 JavaScript:
/****Scripts to warn user of unsaved changes****/
//https://stackoverflow.com/questions/140460
//http://jonstjohn.com/node/23
//Activates the confirm message onbeforeunload.
function setConfirmUnload(on) {
setConfirmAsyncPostBack();
if (on) {
removeCheckFromNoWarnClasses();
fixIEonBeforeUnload();
window.onbeforeunload = unloadMessage
return;
}
window.onbeforeunload = null
}
function unloadMessage() {
return 'You have unsaved changes.';
}
//Moves javascript from href to onclick to prevent IE raising onbeforeunload unecessarily
//http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
function fixIEonBeforeUnload() {
if (!$.browser.msie)
return;
$('a').filter(function() {
return (/^javascript\:/i).test($(this).attr('href'));
}).each(function() {
var hrefscript = $(this).attr('href');
hrefscript = hrefscript.substr(11);
$(this).data('hrefscript', hrefscript);
}).click(function() {
var hrefscript = $(this).data('hrefscript');
eval(hrefscript);
return false;
}).attr('href', '#');
}
//Removes warnings from Save buttons, links, etc, that have been can be given "no-warn" or "no-warn-validate" css class
//"no-warn-validate" inputs/links will only remove warning after successful validation
//use the no-warn-validate class on buttons/links that cause validation.
//use the no-warn class on controls that have CausesValidation=false (e.g. a "Save as Draft" button).
function removeCheckFromNoWarnClasses() {
$('.no-warn-validate').click(function() {
if (Page_ClientValidate == null || Page_ClientValidate()) {
setConfirmUnload(false);
}
});
$('.no-warn').click(function() {
setConfirmUnload(false);
});
}
//Adds client side events to all input controls to switch on confirmation onbeforeunload
function enableUnsavedChangesWarning() {
$(':input').one('change', function() {
window.onbeforeunload = function() {
return 'You have unsaved changes.';
}
});
removeCheckFromNoWarnClasses();
}
在我的 ASP.NET 页面中,当用户进行更改时:
if (changed)
{
...
//Confirm unload if there are unsaved changes.
//NB we also have to call fixIEonBeforeUnload() to fix links, done in in page load to include links that are rendered during callbacks
ScriptManager.RegisterStartupScript(Page, GetType(), "unsavedchanges", "setConfirmUnload(true);", true);
}
else
...