我正在使用我在此处另一篇文章中找到的一些代码,它运行良好,当您尝试在保存更改之前关闭页面时,它会提示您并询问您是否要留在该页面上。问题是,如果单击保存按钮(带有回发的 asp 按钮),它会给您相同的消息。
所以我基本上需要停止它在保存按钮的回发中显示。
var form_clean;
// serialize clean form
$(function () {
form_clean = $("form").serialize();
});
// compare clean and dirty form before leaving
window.onbeforeunload = function (e) {
var form_dirty = $("form").serialize();
if (form_clean != form_dirty) {
return 'There is unsaved form data.';
}
};
最佳答案
我建议使用一个标志来表示您正在进行保存并且该规则不应适用。像这样:
var form_clean;
var checkDirty = true;
//this should be called when the save button is clicked, but prior to the page post
function onSave(){
checkDirty = false;
}
window.onbeforeunload = function (e) {
if(checkDirty){
var form_dirty = $("form").serialize();
if (form_clean != form_dirty) {
return 'There is unsaved form data.';
}
}
};
我还建议您在 DOM 完全准备就绪后设置 form_clean
变量,这样可以确保序列化正确的数据:
$(document).ready(function(){
form_clean = $("form").serialize();
});
一旦页面重新加载,该标志应在回发后自动重置
如果您在设置 onSave
函数方面需要帮助,您可以使用这个:
$("#mySubmitButtonID").click(function(){
onSave();
});
关于c# - 如何检查是否脏,但保存时不检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19925397/