簡體   English   中英

如何將外部鏈接與javascript匹配(但忽略子域)?

[英]How to match external links with javascript (but ignore subdomains)?

我有以下(jquery)選擇器,用於尋找外部鏈接。

這有效,並且忽略包含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;
            });
        }
});
$('a').filter(function() {      
        return this.hostname && this.hostname !== location.hostname && this.hostname.indexOf('.'+location.hostname)!=-1
      })

好吧,如果您知道子域名相對於站點的主機名是什么樣的,則可以使用它來制作一個正則表達式。 例如,如果您的主機名始終為xyz,則可以拆分主機名的最后兩部分,並忽略其主機名以相同方式結尾的所有錨點。

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM