如何防止IE中的javascript:href链接触发window.onbeforeunload? [英] How can I prevent window.onbeforeunload from being triggered by javascript: href links in IE?

查看:115
本文介绍了如何防止IE中的javascript:href链接触发window.onbeforeunload?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的表单建立一个故障保险柜,它将警告用户,如果他们离开页面,其表单数据将丢失(类似于gmail所做的事情).

I'm building a fail safe for my form that is going to warn users that if they leave the page their form data will be lost (similar to what gmail does).

window.onbeforeunload = function () {    
        if (formIsDirty) {
            return "You have unsaved data on this form. Don't leave!";
        }
}

以上功能在firefox中效果很好,但在IE中,它是由任何href链接触发的,即使是指向javascript而不是其他页面的链接也是如此.

The above function works great in firefox, but in IE it is triggered by any href link, even ones that are links to javascript and not other pages.

例如....

<a href='javascript:someFunction();'>click</a>

我想知道是否有任何方法可以解决此问题,因为我不希望用户在单击页面上的按钮时就认为他们正在离开页面. 我无法选择重写所有各种链接,因为它们是内置的并且数量众多.

I'm wondering if there is any way to get around this, as I do not want the user thinking that they are leaving the page when they are simply clicking a button on it. I do not have the option of rewriting all the various links as they are built in and numerous.

有什么想法吗?

推荐答案

您可以在悬停这些链接时删除并重新分配onbeforeunload:

You may remove and re-assign the onbeforeunload when hovering those links:

jQuery(
  function($)
  {
      //store onbeforeunload for later use
    $(window).data('beforeunload',window.onbeforeunload);  

      //remove||re-assign onbeforeunload on hover 
    $('a[href^="javascript:"]')
      .hover( 
             function(){window.onbeforeunload=null;},
             function(){window.onbeforeunload=$(window).data('beforeunload');}
            );

  }
);

这篇关于如何防止IE中的javascript:href链接触发window.onbeforeunload?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆