锚点击功能在 Firefox 中不起作用

anchors click function not working in firefox

此代码:

a = document.createElement('a')
a.setAttribute('href','http://www.google.de')
a.click()

在 chrome 工作。它按预期打开 www.google.de。但在 Firefox 中它什么都不做。 为什么以及如何让它发挥作用?

我在 ubuntu linux 15.04.

上使用 firefox 40.0.3

Firefox 可能不会打开 link,因为您从未将它添加到 DOM。

您可以将元素添加到 DOM 并使用 css display:none 从页面中隐藏它。

但是,更标准的方法是使用 javascript window.open() 方法或 window.location.href 方法,具体取决于您想要的行为。

使用以下内容:

var a = document.createElement('a')
a.setAttribute('href','http://www.google.de');
document.getElementsByTagName('body')[0].appendChild(a);
a.click();