2011-10-05 96 views
3

我試圖在我的web應用程序中實施「未保存的更改」警告,但我努力使這項工作正常進行。我知道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; 
     } 
    }); 
} 

感謝。 此致敬禮。

回答

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;     
} 
+0

謝謝您的回答,但它是不是因爲你正在使用onbeforeunload而據我知道你不能顯示自定義的div,而不是從瀏覽器的默認彈出完全是我問。我對嗎? –

+0

如果您願意,可以使用自定義div;您只需要從用戶那裏獲得某種類型的是/否/真/假輸入,以告訴瀏覽器不要回發。 –

+0

這不起作用。 'onbeforeunload'的事件處理程序中不允許確認調用。請參閱http://stackoverflow.com/questions/276660/how-can-i-override-the-onbeforeunload-dialog-and-replace-it-with-my-own,http://stackoverflow.com/questions/12132060/confirm-on-window-onbeforeunload或http://stackoverflow.com/questions/1335727/onbeforeunload-confirmation-screen-customization – qff