【发布时间】:2011-08-29 03:26:10
【问题描述】:
当用户离开页面时,我正在运行一个对话框。唯一的事情是它运行了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();
});
});
【问题讨论】:
-
您需要返回
false,否则事件会继续到unload,因此会关闭窗口... -
如果返回 false,大多数浏览器会打开一个默认对话框:“留下”或“离开”
-
@balexandre: 从
beforeunload返回false只会制作一个带有“false”的警告框。 -
复制an example的时候,尽量理解后再编辑。
e.$('#confirmDialog')没有任何意义。