本文介绍了Javascript / jQuery:以编程方式关注链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript代码中,我想以编程方式让浏览器跟随我的页面上的链接。简单情况:

 < a id =foohref =mailto:[email protected]>某事< / A> 






 函数goToBar(){
$('#foo')。trigger('follow');
}

这是假设,因为它实际上不起作用。不,触发点击不会这样。



我知道窗口.location window.open 但这些不同于本地链接 - 在某些方面对我很重要:a)在< base /> 元素,以及b)在 mailto URLs的情况下。后者尤其重要。至少在Firefox中,调用 window.location.href =mailto:[email protected]会导致窗口的 unload 处理程序来触发,而只要点击一个 mailto 链接就不会,据我所知。



我正在寻找一种方法来触发浏览器对JavaScript代码链接的默认处理。



这种机制是否存在?特别是针对工具包的回答也很受欢迎(特别是对于Gecko)。

解决方案

据我所知,window.location完全符合你的正在寻找,触发浏览器的默认链接点击行为。



一些浏览器在任何事件被触发或实际的href被更改之前注意到协议。
$ b

  window.location =mailto:[email protected]; 

尝试下面提到的小提琴演示,我得到以下结果:




  • Chromium:使用按钮和链接触发 onbeforeunload
  • Firefox触发 onbeforeunload 仅用于按钮

  • Safari:永远不会触发 onbeforeunload

  • Opera:与Safari相同



因此,防止卸载的好方法 code>发生的事件是在 beforeunload 中返回false。


In Javascript code, I would like to programmatically cause the browser to follow a link that's on my page. Simple case:

<a id="foo" href="mailto:[email protected]">something</a>


function goToBar() {
   $('#foo').trigger('follow');
}

This is hypothetical as it doesn't actually work. And no, triggering click doesn't do it.

I am aware of window.location and window.open but these differ from native link-following in some ways that matter to me: a) in the presence of a <base /> element, and b) in the case of mailto URLs. The latter in particular is significant. In Firefox at least, calling window.location.href = "mailto:[email protected]" causes the window's unload handlers to fire, whereas simply clicking a mailto link does not, as far as I can tell.

I'm looking for a way to trigger the browser's default handling of links, from Javascript code.

Does such a mechanism exist? Toolkit-specific answers also welcome (especially for Gecko).

解决方案

As far as I know, window.location does exactly what you are looking for, triggering the browser's default link clicking behavior.

Some browsers notice the protocol before any events are fired or the actual href is changed.

window.location = "mailto:[email protected]";

Trying the fiddle demo mentioned below I get the following results:

  • Chromium: fires onbeforeunload with the button and link
  • Firefox fires onbeforeunload only for the button
  • Safari: never fires onbeforeunload
  • Opera: same as Safari

So a good way to prevent the unload event from being fired is by returning false in beforeunload.

这篇关于Javascript / jQuery:以编程方式关注链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:22