2012-03-27 21 views
5

我正在开发一个企业应用程序,其中表单是动态生成的,我们无法控制代码。大多数表单控件具有以下与之关联的onbeforeunload - 绑定到选择性事件

<select name="s_10_1_1_0" onchange = 'SWESubmitForm(document.SWEForm10_0,s_5,"","1-E0RHB7")' id='s_10_1_1_0' tabindex=1997 > 

<input type="text" name='s_10_1_11_0' value='' onchange = 'SWESubmitForm(document.SWEForm10_0,s_7,"","1-E0RHB7")' id='s_10_1_11_0' tabindex=1997 maxlength="30"> 

代码,我们想提出当用户试图浏览到使用页眉或页脚的链接其他页面的确定取消对话框。

我已经习惯了以下代码来绑定onbeforeunload事件,并向用户展示一个ok取消对话框。

//this identifies the unique page name 
var viewName = $('input[name="SWEView"]').val(); 
// if I am on desired page bind the event so that now dialog is presented to user 
if(viewName == "XRX eCustomer Create Service Request View"){ 
    $(window).bind('beforeunload', function(){ 
    return 'Your Inquiry has not been submitted yet.'; 
}); 
} 

但问题是,这个对话框出现,每次用户更改表单中任何字段的值(我相信这是由于目前的onchange事件SWESubmitForm代码)。

我想onbeforeunload对话框来如果用户单击任何其他链接外的形式或换句话说绑定onbeforeunload选择性事件(包括关闭窗口)在页面上。

请帮忙

回答

6

.onbeforeunload()是全球性的。只有一些离开页面的方式才能触发它。如果安装了事件处理程序,无论浏览者如何离开页面,它都会触发。

您可以跟踪自己的内部状态,并决定是否在onbeforeunload()处理程序提示任何东西,或只是返回任何结果(所以没有及时作出)。

所以,你可以有这样的代码:

//this identifies the unique page name 
var viewName = $('input[name="SWEView"]').val(); 
// if I am on desired page bind the event so that now dialog is presented to user 
if(viewName == "XRX eCustomer Create Service Request View"){ 
    $(window).bind('beforeunload', function() { 
     // figure out whether you need to prompt or not 
     if (myStateSaysToPrompt) { 
      return 'Your Inquiry has not been submitted yet.'; 
     } else { 
      return; // no prompt 
     } 
    }); 
} 

更新

由于这是对谷歌越来越多的观点相当高这将是值得注意的是,这个答案不再起作用。

$(window).bind('beforeunload', function() { 

请注意,绑定事件时不再有“开”。在更高版本的jQuery中使用之前的onbeforeunload将不会导致任何结果。