gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:52:42 26 4
gpt4 key购买 nike

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

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

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 进行解释,因为它的代码更少:

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 方便的委托(delegate)处理,一个(非常)可怜的人的实现可能看起来像:

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

这允许您页面上的所有 链接在不调用beforeunload 处理程序的情况下离开。我相信您可以弄清楚如何自定义它,如果您只想允许它用于一组特定的链接(您的问题不是特别清楚)。

关于javascript - 触发window.onbeforeunload时如何检测链接是否被点击?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15277403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com