本文介绍了如何访问触发beforeunload的JavaScript href事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问导致beforeunload事件的事件。具体来说,如果我点击指向另一个页面的链接,我想知道在beforeunload事件处理程序中链接是什么。

I would like to access the event that caused a beforeunload event. Specifically, if I click on a link to another page, I would like to know what the link was in the beforeunload event handler.

通过这种方式,我会执行根据URL的内容,在beforeunload事件处理程序中执行不同的操作。

In this way, I would be perform different actions in the beforeunload event handler according to what the URL was.

例如'http:'或'https:'警告用户丢失未保存的更改; 'mailto:'或'skype:'不警告用户,因为页面实际上不会被卸载。

Eg 'http:' or 'https:' warn user about losing unsaved changes; 'mailto:' or 'skype:' don't warn user because page is not actually going to be unloaded.

我正在尝试为问题建立一个很好的解决方案像这样:

I am trying to build a good solution to a problem like this:mailto link (in chrome) is triggering window.onbeforeunload - can i prevent this?

推荐答案

我已经准备好了告诉你这是不可能的,因为当你检查出event.target,event.originaltarget等时,onbeforeunload事件只报告被窗口触发。但是,如果你覆盖window.onclick,我们可以修改该方法来注册哪个元素最后一次点击页面。然后,通过为window.onbeforeunload提供代码,我们可以指定新行为来检查最后点击的元素的href。万岁,啤酒!

I was all prepared to tell you this was impossible because the onbeforeunload event only reports to have been triggered by the window when you check out event.target, event.originaltarget, etc. If you override window.onclick, however, we can modify that method to register which element was last clicked on the page. Then, by providing code for window.onbeforeunload, we can specify new behavior that will check for the href of the element which was clicked last. Hooray, beer!

这里的代码将为您提供您想要的完整信息,纯粹的javascript,并且无需在锚标签中添加任何内容。我还会在preventDefault()中弹出弹出这个页面要求您确认是否要离开 - 您输入的数据可能无法保存。确认框。希望这会有所帮助 - 你可以从这里找出该做什么。

Here's code that will give you exactly the information you want though, in pure javascript and with no cruft to add inside your anchor tags. I've also thrown in the preventDefault() which will pop up the "This page is asking you to confirm that you want to leave - data you have entered may not be saved." confirm box. Hope this helps - you can figure out what to do from here.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>12065389</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        var last_clicked;

        window.onclick = function(e) {
            last_clicked = e.target;
            return true;
        }

        window.onbeforeunload = function(e) {
            var e = e || window.event;
            if (last_clicked.href) {
                alert(last_clicked.href);
                e.preventDefault();
            }
        }
   </script>
</head>
<body>
<a href="http://google.com">google</a>
</body>
</html>

这篇关于如何访问触发beforeunload的JavaScript href事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:52