无法在Jquery中取消绑定窗口beforeunload事件

发布于 2024-10-07 17:27:14 字数 608 浏览 7 评论 0原文

我有一个页面,用户可以在其中拖放对象并将其保存为图像。当用户离开该页面时,会触发 beforeunload 事件。现在,这种情况每次都会发生。我想要做的是,如果用户保存了他的工作,则取消绑定该事件,以便该消息不会再次弹出。为此,我使用了 jQuery 中的解除绑定方法。但是,它似乎不起作用。下面是绑定和解除绑定事件的代码。

var notSaved = function()
{
   return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}
$(window).bind('beforeunload', notSaved);

调用保存方法后,

$(window).unbind('beforeunload', notSaved);

我在这里做错了什么?
此外,save 方法实际上是一个 Ajax 调用。

I have a page where the user can drag and drop objects and save them as an image.When a user navigates away from the page, the event beforeunload is fired. Now, this happens every time. What i want to do is, unbind the event if the user has saved his work, so that the message may not pop up again.To do this i have used the
unbind method in jQuery. But, it does not seem to work. Below is the code for binding and unbinding the events.

var notSaved = function()
{
   return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}
$(window).bind('beforeunload', notSaved);

After save method has been called,

$(window).unbind('beforeunload', notSaved);

What am i doing wrong here?
Also, the save method is actually an Ajax call.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拥醉 2024-10-14 17:27:14

就绑定而言,beforeunload 不能以这种方式可靠地工作。您应该在本地分配它:

window.onbeforeunload = function() {
  return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}

并在您的保存方法中:

window.onbeforeunload = null;

beforeunload doesn't work reliably this way, as far as binding goes. You should assign it natively:

window.onbeforeunload = function() {
  return 'You have not yet saved your work.Do you want to continue? Doing so, may cause loss of your work' ;
}

And in your save method:

window.onbeforeunload = null;
抚笙 2024-10-14 17:27:14
const windowReloadBind = function(message) {
    window.onbeforeunload = function(event) {
        //--- Your logic
        return 'your output';
    }
};

const windowReloadUnBind = function() {
    window.onbeforeunload = function() {
      return null;
    };
};
const windowReloadBind = function(message) {
    window.onbeforeunload = function(event) {
        //--- Your logic
        return 'your output';
    }
};

const windowReloadUnBind = function() {
    window.onbeforeunload = function() {
      return null;
    };
};
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文