我在用户离开页面时运行一个对话框。唯一的问题是它运行了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();
});
});
最佳答案
beforeunload
利用浏览器内置的方法,需要返回一个字符串给它,浏览器会显示该字符串并询问用户是否要离开页面。
您不能使用自己的对话框(或 jQueryUI 模式对话框)来覆盖 beforeunload
。
beforeunload
无法将用户重定向到另一个页面。
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
这将弹出一个警告框,显示“您确定要离开吗?”
并询问用户是否要离开该页面。
(更新:Firefox 不会显示您的自定义消息,它只显示自己的消息。)
如果你想在页面卸载时运行一个函数,你可以使用$(window).unload()
,只是注意它不能阻止页面卸载或重定向页面用户。 (更新:Chrome 和 Firefox 会阻止 unload
中的警报。)
$(window).unload(function(){
alert('Bye.');
});
演示:http://jsfiddle.net/3kvAC/241/
更新:
$(...).unload(...)
是 deprecated从 jQuery v1.8 开始,改为使用:
$(window).on('unload', function(){
});
关于jquery - 对话框运行 1 秒后消失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6063522/