【发布时间】:2010-07-20 14:04:05
【问题描述】:
我已经使用这些页面上描述的技术实现了“未保存的更改”警告:
Client/JS Framework for "Unsaved Data" Protection?
http://kenbrowning.blogspot.com/2009/01/using-jquery-to-standardize.html
这很好用,除了页面上的 DropDownList。它执行 AutoPostBack,我希望 onbeforeunload 触发,因为未保存的更改将丢失,但它不起作用。它应该引发 onbeforeunload 事件吗?我能以某种方式让它引发事件吗?
编辑: DropDownList 位于 UpdatePanel 内,因此这意味着它不会卸载页面,这就是未触发 onbeforeunload 的原因。有什么办法可以以编程方式触发事件吗?还是我必须推出自己的模仿确认对话框?
编辑2 我现在有一个解决方案,可以将对话框添加到来自 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
...
【问题讨论】:
标签: javascript asp.net jquery javascript-events