2010-05-26 70 views
50

如何測試鏈接是外部鏈接還是內部鏈接?請注意:測試鏈接是否使用jQuery/javascript進行外部鏈接?

  1. 我不能硬編碼本地域。
  2. 我無法測試「http」。我可以通過http絕對鏈接輕鬆地鏈接到我自己的網站。
  3. 我想使用jQuery/javascript,而不是css。

我懷疑答案位於location.href的某處,但解決方案無視我。

謝謝!

+0

你要檢查它鏈接被點擊時,或在頁面加載? – Elangovan 2010-05-26 07:42:12

+0

頁面加載,謝謝。 – Matrym 2010-05-26 07:52:58

+1

你的回答不起作用。所有檢查應該在'element.href'(從DOM)完成,而不是'$(element).attr('href')'。證明:http://jsfiddle.net/rahzy/1/請接受肖恩的答案。 – Nowaker 2011-10-26 14:49:15

回答

33
var comp = new RegExp(location.host); 

$('a').each(function(){ 
    if(comp.test($(this).attr('href'))){ 
     // a link that contains the current host   
     $(this).addClass('local'); 
    } 
    else{ 
     // a link that does not contain the current host 
     $(this).addClass('external'); 
    } 
}); 

注意:這僅僅是一個快速&骯髒的例子。它將匹配所有href =「#anchor」鏈接 作爲外部。這可能會通過進行一些額外的RegExp檢查而得到改進。


更新2016年11月17日

這個問題仍然有大量的流量,我被一噸的人告訴我,這接受的解決方案會多次失敗。正如我所說,這是一個非常快速和骯髒的答案,以顯示如何解決這個問題的主要方式。更復雜的解決方案是使用可在<a>(錨點)元素上訪問的屬性。就像@Daved在這個答案中已經指出的那樣,關鍵是要比較hostname與當前的window.location.hostname。我寧願比較hostname性質,因爲他們從來沒有包括其中包含的host財產,如果從80

不同的port所以在這裏,我們去:藝術的

$('a').each(function() { 
    if(location.hostname === this.hostname || !this.hostname.length) { 
     $(this).addClass('local'); 
    } else { 
     $(this).addClass('external'); 
    } 
}); 

州:

Array.from(document.querySelectorAll('a')).forEach(a => { 
    a.classList.add(location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external'); 
}); 
+0

這工作得很好,儘管如果別人有更優雅的解決方案,我會延遲答案。出於好奇,爲什麼錨點鏈接註冊爲外部? – Matrym 2010-05-26 08:05:35

+7

我很確定這不會與相關網址一起使用。 'attr'應該返回屬性,而不是屬性(該屬性可能被解析,而不是屬性)。 – 2010-05-26 10:12:31

+10

http://jsfiddle.net/zuSeh/驗證此方法不適用於相關網址。 – 2010-05-26 10:14:50

0

是的,我相信你可以檢索當前的域名與location.href。另一種可能性是創建一個鏈接元素,將src設置爲/,然後檢索規範URL(如果您使用一個URL而不一定是域名,將檢索基本URL)。

也看到這個帖子:Get the full URI from the href property of a link

35

和無jQuery的方式

var nodes = document.getElementsByTagName("a"), i = nodes.length; 
var regExp = new RegExp("//" + location.host + "($|/)"); 
while(i--){ 
    var href = nodes[i].href; 
    var isLocal = (href.substring(0,4) === "http") ? regExp.test(href) : true; 
    alert(href + " is " + (isLocal ? "local" : "not local")); 
} 

所有的HREF不開始http(HTTP://,https://開頭):

external.test('some url'); // => true or false 
+1

這是驗證的方式 – 2010-05-26 08:28:31

+1

這個答案更準確。親屬網址也很重要。 – Savageman 2010-05-26 22:37:46

+0

如果我沒有弄錯,「($ | /」實際上應該是「($ | /)」,並用右大括號 – 2012-07-25 08:08:35

6
var external = RegExp('^((f|ht)tps?:)?//(?!' + location.host + ')'); 

使用自動處理路徑。

forexample:/測試

 hostname = new RegExp(location.host); 
      // Act on each link 
      $('a').each(function(){ 

      // Store current link's url 
      var url = $(this).attr("href"); 

      // Test if current host (domain) is in it 
      if(hostname.test(url)){ 
       // If it's local... 
       $(this).addClass('local'); 
      } 
      else if(url.slice(0, 1) == "/"){ 
       $(this).addClass('local'); 
      } 
      else if(url.slice(0, 1) == "#"){ 
       // It's an anchor link 
       $(this).addClass('anchor'); 
      } 
      else { 
       // a link that does not contain the current host 
       $(this).addClass('external');       
      } 
     }); 

也有文件的下載名爲.zip的問題(本地連接外置),其可以使用類「本地下載」或「外部下載」。但還沒有找到解決方案。

+1

+1爲正則表達式,儘管它不能完全解決問題 – feeela 2012-12-08 21:58:20

6

你忘了一個,如果您使用的是相對什麼地方

+0

並非所有的相對URL都以'/'開頭。你可以引用像'images/logo.png'這樣的文件夾,它是你當前位置的一個文件夾。在這種情況下,你在相對URL中引用了一個相對路徑,它在你網站的不同目錄中會有不同的含義。 '/ images/logo.png'是它運行的任何站點的絕對路徑(因此是相對性的)。您的代碼不會包含像'images/logo.png'這樣的相對路徑。 – 2014-05-08 21:54:37

48

我知道這個帖子是舊的,但它仍然顯示在結果的頂部,所以我想提供另一種方法。我看到了一個錨元素的所有正則表達式檢查,但爲什麼不使用window.location.host並檢查元素的host屬性?

function link_is_external(link_element) { 
    return (link_element.host !== window.location.host); 
} 

使用jQuery:

$('a').each(function() { 
    if (link_is_external(this)) { 
     // External 
    } 
}); 

,並與普通的JavaScript:

var links = document.getElementsByTagName('a'); 
for (var i = 0; i < links.length; i++) { 
    if (link_is_external(links[i])) { 
     // External 
    } 
} 
+7

這是唯一對我有意義的答案 - 其他答案是過度工程化的。有沒有反對這種方法的爭論? – tremby 2014-10-08 01:01:44

+0

上面的jQuery在Safari中適用於我,並處理其他人處理的所有問題 - 本地錨,相對URL,跨協議URL等。注意:http://www.example.com和https:/ /www.example.com將被標記爲內部;這可能對你很重要。 – 2015-06-17 00:05:51

+1

這是最好的答案。這使用了'a。主機「屬性,這對於普通JavaScript開發人員來說可能是未知的(包括我在閱讀本文之前)。 – dana 2015-11-10 17:47:53

7

這裏有一個jQuery選擇只有外部鏈接:

$('a[href^="(http:|https:)?//"])') 

jQuery選擇僅適用於內部鏈接(不包括瀘定在同一頁內的散列鏈接)需要一個比較複雜:

$('a:not([href^="(http:|https:)?//"],[href^="#"],[href^="mailto:"])') 

附加過濾器可以被放置在:not()條件內,並根據需要通過額外的逗號分隔。

http://jsfiddle.net/mblase75/Pavg2/


或者,我們可以篩選使用香草的JavaScript href屬性,它始終是一個絕對URL的內部鏈接:

$('a').filter(function(i,el) { 
    return el.href.indexOf(location.protocol+'//'+location.hostname)===0; 
}) 

http://jsfiddle.net/mblase75/7z6EV/

+0

+1:OK有辦法贊成票再次爲這個答案:) – 2014-06-06 15:43:01

+0

第一個不爲「//代碼工作.jquery.com/jquery.min.js「是一個完全合法的URL,但不是內部的。協議和冒號不是必需的,因爲瀏覽器將使用當前網站正在使用的任何內容(半分類協議相對URL)。 – mikesir87 2014-10-21 19:04:47

+1

@ mikesir87好點,更新。 – Blazemonger 2014-10-21 19:15:28

0

對於那些有興趣,我做了一個帶有檢查的if塊的三元版本,以查看該元素具有哪些類別以及哪些類別s被附上。

$(document).ready(function() { 
    $("a").click(function (e) { 

     var hostname = new RegExp(location.host); 
     var url = $(this).attr("href"); 

     hostname.test(url) ? 
     $(this).addClass('local') : 
     url.slice(0, 1) == "/" && url.slice(-1) == "/" ? 
     $(this).addClass('localpage') : 
     url.slice(0, 1) == "#" ? 
     $(this).addClass('anchor') : 
     $(this).addClass('external'); 

     var classes = $(this).attr("class"); 

     console.log("Link classes: " + classes); 

     $(this).hasClass("external") ? googleAnalytics(url) : 
     $(this).hasClass("anchor") ? console.log("Handle anchor") : console.log("Handle local"); 

    }); 
}); 

的谷歌分析位被忽略,但是這是你可能會喜歡做一些與URL現在你知道它是什麼類型的鏈接。只需在三元塊內添加代碼即可。 如果您只想檢查1種鏈接,則用if語句替換三元組。

編輯添加我遇到的問題。我的一些hrefs是「/ Courses /」。我做了一個本地頁面的檢查,檢查href的開始和結尾是否有斜線。雖然剛開始時檢查'/'可能就足夠了。

1

您可以使用is-url-external模塊。

var isExternal = require('is-url-external'); 
isExternal('http://stackoverflow.com/questions/2910946'); // true | false 
0

我用這個函數的jQuery:

$.fn.isExternal = function() { 
    var host = window.location.host; 
    var link = $('<a>', { 
    href: this.attr('href') 
    })[0].hostname; 
    return (link !== host); 
}; 

用法爲:$('a').isExternal();

例子:https://codepen.io/allurewebsolutions/pen/ygJPgV