问题描述
如何显示您确定要离开页面吗?当用户实际尝试关闭页面时(单击浏览器窗口或选项卡上的X按钮)而不是当他试图离开页面时(单击另一个链接)。
How can I display "Are you sure you want to leave the page?" when the user actually tries to close the page (click the X button on the browser window or tab) not when he tries to navigate away from the page (click on another link).
我的客户希望在用户尝试关闭页面时显示一条消息您确定要离开该页吗?您的购物车中仍有商品。
My client wants a message to appear when the user tries to close the page "Are you sure you want to leave the page? You still have items in your shopping cart."
不幸的是 $(窗口).bind('beforeunload')
仅在用户关闭页面时才会触发。
Unfortunately $(window).bind('beforeunload')
doesn't fire only when the user closes the page.
jQuery:
function checkCart() {
$.ajax({
url : 'index.php?route=module/cart/check',
type : 'POST',
dataType : 'json',
success : function (result) {
if (result) {
$(window).bind('beforeunload', function(){
return 'leave?';
});
}
}
})
}
推荐答案
你c这是通过使用 JQuery 来实现的。
You can do this by using JQuery.
对于示例,
<a href="your URL" id="navigate"> click here </a>
你的 JQuery
将是,
$(document).ready(function(){
$('a').on('mousedown', stopNavigate);
$('a').on('mouseleave', function () {
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
});
});
function stopNavigate(){
$(window).off('beforeunload');
}
要获得离开消息提醒将是,
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
$(window).on('unload', function(){
logout();
});
此解决方案适用于所有浏览器,我已对其进行了测试。
This solution works in all browsers and I have tested it.
这篇关于关闭(不离开)页面时jquery beforeunload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!