2010-02-24 52 views
2

我有以下(jquery)选择器寻找外部链接。如何使用JavaScript匹配外部链接(但忽略子域名)?

这工作,而忽略包括所有链接location.hostname(例如www.domain.com)

我的问题是,如何延长这也忽略链接到你的网站的子域? (例如new.domain.com)

$('a').each(function() { 

    var href = $(this).attr('href'); 

    if(this.hostname && this.hostname !== location.hostname) 
    {  
     $(this) 
      .removeAttr('target') 
      .attr('rel', 'external')     
      .attr('title', href) 
      .click(function() { 
       window.open($(this).attr('href')); 
       return false; 
      }); 
     } 
}); 

回答

0

那么,如果你知道你的子域名是什么样子相对于网站的主机名,你可以只让一个正则表达式了这一点。例如,如果您的主机名始终是x.y.z,那么您可以拆分最后两个主机名,并忽略主机名以相同方式结束的任何锚。

var parts = location.hostname.split('.'), 
    domainMatch = new RegExp('[^.]*\\.' + parts[1] + '\\.' + parts[2] + '$'); 

if (this.hostname && !domainMatch.test(this.hostname)) { 
// ... 
} 
+0

您还可能需要验证零件数组的长度。可能是这个域只包含'domain.com'。 – cmptrgeekken 2010-02-24 15:03:53

+0

是的,就像我说的那样,这取决于相关域的设置。制作适用于任何域/子域系列的脚本可能相当困难。 – Pointy 2010-02-24 15:18:43

4
$('a').filter(function() {  
     return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1 
     }) 
相关问题