【问题标题】:onbeforeunload - bind to selective eventsonbeforeunload - 绑定到选择性事件
【发布时间】:2012-04-10 13:39:28
【问题描述】:

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

<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 与页面上的选择性事件(包括关闭窗口)联系起来,我想打开 onbeforeunload 对话框。

请帮忙

【问题讨论】:

    标签: jquery onbeforeunload siebel


    【解决方案1】:

    .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 将不会导致任何事情发生。

    【讨论】:

      猜你喜欢
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2020-10-15
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 2019-11-01
      相关资源
      最近更新 更多