onbeforeunload - 绑定到选择性事件

5

我正在开发一个企业应用程序,其中表单是动态生成的,我们无法控制代码。表单中的大多数控件都有以下代码与之相关:

<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 事件,并向用户呈现了一个“确定/取消”对话框。
//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对话框绑定到页面上的选择性事件(包括关闭窗口)时,才会出现该对话框。
请帮忙。
1个回答

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() {

请注意,绑定事件时不再使用'on'。在后续版本的jQuery中使用以前的onbeforeunload将导致什么也不发生。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接