且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在触发window.onbeforeunload时检测链接是否被点击?

更新时间:2023-11-28 09:02:58

你正在寻找延期事件处理。我将解释使用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).