gpt4 book ai didi

javascript - 当尝试禁用 anchor 链接的 onbeforeunload 时,在 mouseclick 之前调用 mouseleave

转载 作者:行者123 更新时间:2023-12-02 19:43:37 24 4
gpt4 key购买 nike

我正在尝试禁用页面上所有 anchor 链接的 onbeforeunload,以便仅在关闭浏览器窗口/选项卡时触发它。

我是这样做的:

对于所有 anchor ,onmouseover,我将 null 值存储到 window.onbeforeunload 函数。然后,onmouseleave,我恢复了window.onbeforeunload函数:

$(function () {
SetupOnNavigateAway();
});

function OnBeforeUnload(oEvent) {
return "Are you sure you want to close this page?";
}

function SetupOnNavigateAway() {
window.onbeforeunload = OnBeforeUnload;
$(window).data('beforeunload', window.onbeforeunload);
$('body').delegate('a', 'hover', function (event) {
if (event.type === 'mouseenter' || event.type === "mouseover")
window.onbeforeunload = null;
else
window.onbeforeunload = $(window).data('beforeunload');
});
}

我的问题是,对于某些浏览器版本,当我单击链接时,mouseleave 事件会在 mouseclick 事件之前触发。 (我的光标尚未离开链接)因此 onbeforeunload 函数在不需要调用时会被调用..

示例:

现在的处理方式是这样的:

  1. 将鼠标移到按钮上:window.onbeforeunload = null
  2. 将鼠标从按钮上移开:window.onbeforeunload = OnBeforeUnload
  3. 将鼠标移到按钮上:window.onbeforeunload = null
  4. 将光标停留在按钮上并单击:window.onbeforeunload = OnBeforeUnload,重定向

它应该是这样工作的:

  1. 将鼠标移到按钮上:window.onbeforeunload = null
  2. 将鼠标从按钮上移开:window.onbeforeunload = OnBeforeUnload
  3. 将鼠标移到按钮上:window.onbeforeunload = null
  4. 将光标停留在按钮上并单击:重定向(window.onbeforeunload 仍然为空)

那么如何防止在单击 anchor 时发生 mouseleave 事件?

最佳答案

您是否尝试过在单击时取消绑定(bind) mouseleave 的事件监听器:

$('body').delegate('a', 'click', function (event) {
$(this).unbind('mouseleave');
});

关于javascript - 当尝试禁用 anchor 链接的 onbeforeunload 时,在 mouseclick 之前调用 mouseleave,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10102523/

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