链接到锚点(ajax url)没有't调用BeforeUnload

Link to anchor (ajax url) doesn't call onBeforeUnload

本文关键字:BeforeUnload 调用 没有 url ajax 链接      更新时间:2023-09-26

我有一个onbeforeunload事件:

$().ready(function() { 
  window.onbeforeunload=function() { return "haha" };
});

我的链接是这样的(ajax网站):

<a href="#pageX" /> 

但onbeforeunload从未被调用。我能做什么?

感谢

我猜,由于您试图绑定到onbeforeunload并返回一个字符串,因此您希望在AJAX网站上为用户提供一个"您确定要离开此页面吗"对话框。

在这种情况下,您可能需要通过将单击处理程序绑定到链接来进行一些不同的处理。因此,您可以在进行确认之前阻止哈希更改。

类似于:

$('a[href^="#"]').live('click',function(e){
    if( //should we be confirming first? ) {
        //put your confirmation code here either using default JS windows or your own CSS/jQueryUI dialog boxes
        // this code should either cache the url of the link that was clicked and manually update the location with it when the user confirms the dialog box (if you're using JQUI windows) or simply use JS confirmation boxes and based on the response, all you need to do is return; and the link click will handle normally
        e.preventDefault(); //prevent the link from changing the hash tag just yet
        e.stopImmediatePropagation(); //prevent any parent elements from firing any events for this click
    }
} );

别误会,你是认真的吗?

该链接只是引用了一个散列标记,因此,它不会离开当前站点,也不会调用onbeforeunloadunload

如果存在任何*click事件处理程序bound to that anchor aswell, there must be something in the event handler code which really forces the current site to get unloaded (位置。href`例如)。

如果您只是通过Ajax切换HTML,那么也没有onbeforeunload

您可以将一个处理程序绑定到onhashchange事件(检查浏览器兼容性),但如果您的url/hash发生任何更改,就会触发该处理程序。

您可能正在查找onhashchange事件:https://developer.mozilla.org/en/DOM/window.onhashchange