如何在触发window.onbeforeunload时检测链接是否被点击? [英] how to detect if a link was clicked when window.onbeforeunload is triggered?

查看:90
本文介绍了如何在触发window.onbeforeunload时检测链接是否被点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有window.onbeforeunload正确触发。它显示一个确认框,以确保用户知道他们正在导航(关闭)窗口,并且任何未保存的工作都将被删除。

I have window.onbeforeunload triggering properly. It's displaying a confirmation box to ensure the user knows they are navigating (closing) the window and that any unsaved work will be erased.

我有一个独特的情况我不喜欢如果用户通过单击链接导航离开页面,则不希望触发此操作,但我无法弄清楚如何检测是否已在函数内单击链接以暂停该功能。这就是我的代码:

I have a unique situation where I don't want this to trigger if a user navigates away from the page by clicking a link, but I can't figure out how to detect if a link has been clicked inside the function to halt the function. This is what I have for code:

window.onbeforeunload = function() {
var message = 'You are leaving the page.';

/* If this is Firefox */
if(/Firefox[\/\s](\d+)/.test(navigator.userAgent) && new Number(RegExp.$1) >= 4) {
  if(confirm(message)) {
    history.go();
  } 
  else {
    window.setTimeout(function() {
      window.stop();
    }, 1);
  }
}
/* Everything else */
else {
  return message;
}
}


推荐答案

你正在寻找延期事件处理。我将解释使用jQuery,因为代码较少:

You're looking for deferred event handling. I'll explain using jQuery, as it is less code:

window._link_was_clicked = false;
window.onbeforeunload = function(event) {
  if (window._link_was_clicked) {
    return; // abort beforeunload
  }
  // your event handling
};

jQuery(document).on('click', 'a', function(event) {
  window._link_was_clicked = true;
});

一个(非常)穷人的实现没有jQuery的方便的委托处理可能看起来像:

a (very) poor man's implementation without jQuery's convenient delegation handling could look like:

document.addEventListener("click", function(event) {
  if (this.nodeName.toLowerCase() === 'a') {
    window._link_was_clicked = true;
  }
}, true);

这允许页面上的所有链接离开而不调用 beforeunload 处理程序。我确定你可以弄清楚如何自定义这个,如果你只想在特定的链接集中允许这个(你的问题不是特别清楚)。

this allows all links on your page to leave without invoking the beforeunload handler. I'm sure you can figure out how to customize this, should you only want to allow this for a specific set of links (your question wasn't particularly clear on that).

这篇关于如何在触发window.onbeforeunload时检测链接是否被点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆