如何检查是否脏,但在保存时不检查

How do I check if dirty, but not when saving?

本文关键字:保存 不检查 是否 何检查 检查      更新时间:2023-09-26

我正在使用我在这里的另一篇帖子中找到的一些代码,它运行良好,当您尝试在保存更改之前关闭页面时,它会提示您并询问您是否要留在页面上。问题是,如果单击保存按钮(带有回发的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();
});