我创建了一个项目,我做一个网站。 在网站的内容有对可访问的外部网页的链接。 与此同时,当用户点击,他将被带往指定的链接的链接之一,他也不会在当前页面了。 我想要做的是在点击链接指定网站出现在一个新的标签,当用户点击链接。 通过这种方式,用户停留在当前页面上他是一个,也可以在新标签中查看其他页面。
我看着在互联网上,发现这其中似乎是有用的:
function externalLinks()
{
var anchors = document.getElementsByTagName("a");
for (var i=0; i<anchors.length; i++)
{
var anchor = anchors[i];
if(anchor.getAttribute("href"))
anchor.target = "_blank";
}
}
window.onload = externalLinks;
我现在面临的问题是,我的网站的导航栏包含锚标记。 如果用户点击在导航栏的链接所以现在它会打开一个新标签。 我想如果用户单击我的网站的内容的链接上这才会发生。 因此,如果用户点击导航栏的链接不应该打开一个新标签,并应只是带他到指定的目标。
我已经尝试添加一个类内容中的所有链接,并使用getElementByClassName,但它仍然没有奏效
任何人都可以帮我这个
你可以使用HTML:
<a target="_blank" href="YourAmazingURL">Click here for Amazing URL</a>
另一个例子:
<a target="_blank" href="http://www.google.com/">Google</a>
这需要目标属性的优势。
目标属性的详细信息: http://www.w3schools.com/tags/att_a_target.asp另外: http://www.w3schools.com/html/html_links.asp
编辑:
对于XHTML,只是这样做:
<a href="YourAmazingURL" onclick="window.open(this.href,'_blank');return false;">Click here for Amazing URL</a>
或者,再次:
<a href="http://www.google.com/" onclick="window.open(this.href,'_blank');return false;">Google</a>
是使用JavaScript这一点,你需要的?
如果没有,你可以只直接添加属性到HTML中的一个标签。
例如: <a href="http://www.google.co.uk" target="_blank">Google</a>
这很可能会为你做它,如果不需要的JavaScript一个更简单的方法。
如果您需要依赖于JavaScript:
基本上你只需要改变你if
-condition(检查是否锚链接指向外部位置或没有)。
所以,相反的if(anchor.getAttribute("href"))
使用if(anchor.getAttribute("href") && anchor.hostname!==location.hostname)
与一些代码清理,你的函数应该如下所示:
function externalLinks() {
for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++) {
var b = c[a];
b.getAttribute("href") && b.hostname !== location.hostname && (b.target = "_blank")
}
}
;
externalLinks();
您要使用document.getElementById("theidgoeshere");
要做到这一点,在您的链接设置id属性,如下所示:
<a href="www.google.com" id="theidgoeshere">Google</a>
然后,在JavaScript
var anchor = document.getElementById("theidgoeshere");
if(anchor.getAttribute("href"))
anchor.target = "_blank";
另外请注意,你可能希望在不的JavaScript做。 只要把target="_blank"
在你的锚标记。