代码之家  ›  专栏  ›  技术社区  ›  meleyal

如何用javascript匹配外部链接(但忽略子域)?

  •  2
  • meleyal  · 技术社区  · 15 年前

    我有以下(jquery)选择器来查找外部链接。

    这是可行的,并忽略所有链接,包括 location.hostname

    我的问题是,如何扩展这一点,也忽略链接到您的网站子域?

    $('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;
                });
            }
    });
    
    2 回复  |  直到 15 年前
        1
  •  4
  •   Sam Dark    15 年前
    $('a').filter(function() {      
            return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1
          })
    
        2
  •  0
  •   Pointy    15 年前

    如果你知道你的子域相对于你的站点的主机名是什么样子的,你就可以用它来做一个正则表达式。例如,如果您的主机名总是x.y.z,那么您可以分割主机名的最后两部分,并忽略主机名以相同方式结束的任何锚定。

    var parts = location.hostname.split('.'),
       domainMatch = new RegExp('[^.]*\\.' + parts[1] + '\\.' + parts[2] + '$');
    
    if (this.hostname && !domainMatch.test(this.hostname)) {
     // ...
    }