对话框运行1秒后消失?

use*_*107 58 jquery jquery-ui

用户离开页面时,我正在运行一个对话框.唯一的事情是它运行1秒并消失?我知道它与此有关bind('beforeunload'),但对话框的死亡时间比你能读到的要快.

我如何阻止这种情况发生?

$(document).ready(function() {  

    // Append dialog pop-up modem to body of page
    $('body').append("<div id='confirmDialog' title='Confirm'><p><span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>Are you sure you want to leave " + brandName + "? <br /> Your order will not be saved.</p></div>");

    // Create Dialog box
    $('#confirmDialog').dialog({
      autoOpen: false,
      modal: true,
      overlay: {
        backgroundColor: '#000',
        opacity: 0.5
      },
      buttons: {
        'I am sure': function() {
          var href = $(this).dialog('option', 'href', this.href);
          window.location.href = href;
        },
        'Complete my order': function() {
          $(this).dialog('close');
        }
      }
    });

    // Bind event to Before user leaves page with function parameter e
    $(window).bind('beforeunload', function(e) {    
        // Mozilla takes the
        var e = $('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
        // For IE and Firefox prior to version 4
        if (e){
            $('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
        }
        // For Safari
        e.$('#confirmDialog').dialog('open').dialog('option', 'href', this.href);
    }); 

    // unbind function if user clicks a link
    $('a').click(function(event) {
        $(window).unbind();
        //event.preventDefault();
        //$('#confirmDialog').dialog('option', 'href', this.href).dialog('open');
    });

    // unbind function if user submits a form
    $('form').submit(function() {
        $(window).unbind();
    });
});
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 153

beforeunload 利用浏览器内置的方法,您需要向其返回一个字符串,浏览器将显示该字符串并询问用户是否要离开该页面.

您不能使用自己的对话框(或jQueryUI模式对话框)来覆盖beforeunload.

beforeunload 无法将用户重定向到另一个页面.

$(window).on('beforeunload', function(){
  return 'Are you sure you want to leave?';
});
Run Code Online (Sandbox Code Playgroud)

这将弹出一个警告框,说明'Are you sure you want to leave?'并询问用户是否要离开页面.

(更新:Firefox不显示您的自定义消息,它只显示自己的消息.)

如果要在页面卸载时运行函数,可以使用$(window).unload(),只需注意它无法阻止页面卸载或重定向用户.(更新:Chrome和Firefox阻止警报unload.)

$(window).unload(function(){
  alert('Bye.');
});
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/3kvAC/241/

更新:

$(...).unload(...)自jQuery v1.8以来已弃用,而是使用:

$(window).on('unload', function(){
});
Run Code Online (Sandbox Code Playgroud)

  • 似乎Firefox现在也阻止了alert() (4认同)