如何显示"您确定要离开页面吗?"当用户实际试图关闭页面时(单击浏览器窗口或选项卡上的X按钮),而不是当用户试图离开页面时(单击另一个链接).

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."

不幸的是,$(window).bind('beforeunload')并不是只有在用户关闭页面时才会触发的.

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?';
        });
       }
    }
  })
}

推荐答案

You can do this by using JQuery.

example美元,

<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');
}

And to get the Leave message alert will be,

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

$(window).on('unload', function(){

         logout();

});

这个解决方案可以在所有浏览器中使用,我已经对其进行了测试.

Jquery相关问答推荐

在不同的行插入不同的值

使用 JQuery 在 span 标签中用逗号分隔页面上的文本

第一次单击后,Ajax addEventListener 停止工作

我正在try 使用 Jquery 打开与帖子相关的特定 comments

如何以十六进制获取元素的背景 colored颜色 代码?

$(document).scrollTop() 总是返回 0

如何使用 jQuery 以编程方式触发对链接的点击?

如何使用 jQuery go 除 HTML 标签?

JSON 服务在失败/错误时应该返回什么

如何通过 Select 插件使用 jQuery 验证?

从 iframe 访问父窗口的元素

调整浏览器大小时调整jqGrid的大小?

如何使用 jQuery 显示忙碌指示器?

循环判断复选框并计算每个选中或未选中的复选框

如何让 JavaScript/jQuery Intellisense 在 Visual Studio 2008 中工作?

jQuery 和 jQuery Mobile 的区别?

jQuery ajax 成功回调函数定义

什么时候应该使用 jQuery deferred 的then方法,什么时候应该使用pipe方法?

删除除一个之外的所有类

JavaScript 在 DOM 中移动元素