onbeforeunload - 绑定到选择性事件

时间:2012-03-27 02:16:41

标签: jquery onbeforeunload siebel

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

<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">

当用户尝试使用页眉或页脚中的链接导航到其他某个页面时,我们想要提供一个ok取消对话框。

我习惯使用以下代码绑定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对话框。

请帮助

1 个答案:

答案 0 :(得分: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将导致没有任何事情发生。

相关问题