如何阻止 <a> 标记的 window.on('beforeUnload') 事件

How do I block the window.on('beforeUnload') event for <a> tag?

本文关键字:on beforeUnload window 事件 何阻止      更新时间:2023-09-26

在我的项目中,当用户想使用 X 按钮关闭窗口/选项卡时,我需要收到用户确认警报。

但是window.on('beforeUnload')也适用于 超链接 .如何阻止此leave page警报<a>标签?

我的 JSP 将具有

<a href="next.jsp" id="navigate"> click here </a>

我的 Jquery 将有 ,

$(document).ready(function(){
    $('#navigate').on('click', function() {
    stopNavigate(event);
    });
    
});
function stopNavigate(event){   
    $(window).off('beforeunload', function(){
        
    });
}

$(window).on('beforeunload', function(){
    return 'Are you sure you want to leave?';
});
$(window).on('unload', function(){
    logout();

});

我不想要用户单击任何links时的leave message alert。我只需要leave message alert用于窗口关闭操作

$(document).ready(function () {
    $('#navigate').on('mouseenter', stopNavigate)
        .on('mouseout', function () {
        $(window).on('beforeunload', windowBeforeUnload);
    });
});
function stopNavigate(event) {
    $(window).off('beforeunload');
}
function windowBeforeUnload() {
    return 'Are you sure you want to leave?';
}
$(window).on('beforeunload', windowBeforeUnload);

演示

试试这个 -

$("a").mousedown(function() {
    $(window).unbind();
});