未保存的更改警告弹出窗口

时间:2011-10-05 14:36:36

标签: javascript jquery asp.net

我正在尝试在我的网络应用程序中实施“未保存的更改”警告,但我正在努力使其正常工作。我知道javascript中存在onbeforeunload事件,但是我被要求使用带有一些花哨格式的自定义div作为模式弹出窗口来提示用户有关那些未保存的更改。

到目前为止我得到的是:

它的作用基本上是绑定一个函数来检查页面是否脏,并在点击任何可能导致回发的链接或按钮等之前用弹出窗口提示用户。我现在遇到的一个问题是,当我按下继续时,所有取消的事件似乎都在运行,而不是仅仅是最后一个。

我知道这不是最好的解决方案,但这是我想到的唯一的事情。欢迎更好的想法:)

jQuery函数在所有其他事件之前绑定事件:

$.fn.bindFirst = function(name, fn) {
    this.bind(name, fn);
    var handlers = this.data('events')[name.split('.')[0]];
    if (handlers.length) {
        var handler = handlers.pop();
        handlers.splice(0, 0, handler);
    }
};

function hideSaveWarning() {
    $("#divSaveWarning").hide();
}

这将设置继续按钮以执行取消的操作

function showSaveWarning(e) {
    $("#divSaveWarning").show();
    $("[id$='_btnContinue']").click(function() {
        e.currentTarget.click();
    });
}

function onClickContinueWithoutSaving() {
    hideSaveWarning();
    setDirtyContent(false);
}

function SetSavePrompt() {
    setDirtyContent(false);
    $(":input, :radio, :button, a").not("[id$='_btnSave']").bindFirst('click', function(e) {
        if (isPageDirty) {
            showSaveWarning(e);
            return false;
        }
    });
}

感谢。 问候。

2 个答案:

答案 0 :(得分:3)

这可以解决这个问题吗?

http://mal.co.nz/code/jquery-dirty-forms/

答案 1 :(得分:1)

我没有对此进行过测试,可能需要进行一些调整,但你应该可以这样做:

JavaScript的:

<script language="javascript" type="text/javascript">              
    var formChanged = false;
    window.onbeforeunload = function() {
        if(!formChanged){
            return;                                   
        }
        return confirm("You have made changes to this form. Do you want to continue without saving these changes?");           
    }        
    function  setDirty() { 
        formChanged = true; 
    }                                
</script> 

代码隐藏:

protected void RegisterClientSaveChangeHandler()
{
    foreach (Control ctrl in Page.Controls)
    {
        if (ctrl != null)
        {
            //make sure it doesn't prompt for save if it's a button click
            if (ctrl is Button | ctrl is LinkButton | ctrl is ImageButton | ctrl is HyperLink)
                ((WebControl)ctrl).Attributes.Add("onclick", "javascript:formChanged=false;");

            //make sure that all user input fields register for prompting when the value changes
            if (ValidateAsInput(ctrl))
                ((WebControl)ctrl).Attributes.Add("onchange", "setDirty()");                
        } 
    }                     
}

private bool ValidateAsInput(Control ctrl)
{
    return ctrl is TextBox | ctrl is CheckBox | ctrl is RadioButton | ctrl is DropDownList | ctrl is RadioButtonList;                
}
相关问题