2013-06-12 40 views
3

我有下面的代码,将增加target="_blank"所有链接:添加目标=“_空白”的所有链接,但内部站点链接

$(function() { 
    $("a[href^='http://']").attr("target","_blank"); 
}); 

如何将我重新写上面的代码为目标,除了所有链接内部链接。

IE:

http://www.my-site.com/ =内部链接

http://www.other-site.com/ =外部链接

此外,我怎么会针对不以http://开始,但不是内部的任何链接?

我正在寻找一个jQuery解决方案。

+0

你想要以'http://'开头的目标是什么样的外部链接?只是'https://'? – Marcel

+0

@Marcel - 我有几个链接从'ftp'开始,但实际上我可以手动添加这些链接。除此之外是'https://' – L84

回答

6

刚刚链中的选择:

$("a[href^='http']:not([href^='http://www.mysite.com'])").attr("target","_blank"); 

这将选择http(所以没有相对的内部)开始,但不与http://www.mysite.com开始(所以不是绝对内部其一)的所有链接。

+0

这很好,很简洁。 – Marcel

+0

使用此解决方案可能会出现性能问题。 – Ohgodwhy

+0

对于支持这些CSS3选择器的现代浏览器来说,并不是真的,浏览器本地处理这些选择,而对于较老的浏览器,Sizzle选择器引擎不仅能在现代计算机上以毫秒为单位执行这种一次搜索。无论如何,它不会比Marcel的解决方案慢很多,它会循环更多的元素并将字符串搜索应用于所有元素。 –

4

我在使用jQuery时使用了以下的JavaScript代码。它还为外部链接添加了一个类,并在Google Analytics中包含跟踪外发链接。如果您不使用Google Analytics,请将其删除。

如果您不希望它击中页面上的所有链接,例如$("#main a[href^=http]"),则可以使用更具体的选择器。

$("a[href^=http]") 
    .each(function(){ 
    // this part checks if the link is external 
    if (this.href.indexOf(location.hostname) == -1){ 
     // add a class for external links 
     $(this).addClass("ext") 
     // make the link open in a new tab/window 
     .attr({ "target":"_blank", "rel":"external" }) 
     // track clicks of external links if you use Google Analytics 
     .click(function(){ 
      _gaq.push(["_trackEvent", "Outgoing link", "click", $(this).attr("href")]); 
     }); 
    } 
    }); 
+0

我唯一的建议是在执行比较时使用.toLowerCase()。 – Ohgodwhy

相关问题