2009-08-04 84 views
10

我想寫一個腳本來確定鏈接是內部的還是外部的。從我的角度來看,這很簡單,所有內部鏈接都是相對的,所以他們以a開頭。所有外部鏈接都以http://開頭 - 迄今爲止都很好。然而,我不知道如何做一個':contains()'以外的任何文本 - 如何在一個屬性中搜索字符串?使用jQuery檢查鏈接是內部的還是外部的

一旦我能做到這一點,我很高興加入目標_blank自己,除非你知道一個更好的方式來做到這一點

回答

22

您可以使用attribute^=value語法來發現與http/開始的HREF:

$("a[href^='http']") // external 

$("a[href^='/']") // internal 

這裏有一個更好的解決方案:您可以添加$('a:external')$('a:internal')選擇將jQuery與下面的插件代碼。任何以http://https://whatever://開頭的網址都被視爲外部網址。

$.expr[':'].external = function (a) { 
     var PATTERN_FOR_EXTERNAL_URLS = /^(\w+:)?\/\//; 
     var href = $(a).attr('href'); 
     return href !== undefined && href.search(PATTERN_FOR_EXTERNAL_URLS) !== -1; 
    }; 

    $.expr[':'].internal = function (a) { 
     return $(a).attr('href') !== undefined && !$.expr[':'].external(a); 
    }; 
+0

謝謝,這看起來像描述的那樣工作。歡呼聲 – chrism 2009-08-04 14:03:08

+8

我說得對,內部網址並不總是以正斜槓開始。對於內部使用$('a [href!= http:] a [href!= https:]')可能會更好。 – kim3er 2009-08-04 14:13:46

+0

對於我正在做的屬性選擇器是更好的選擇。但是,他們有一個小問題。它們應該是$('a [href^=「http」]')和$('a [href^=「/」]') – Tony 2014-01-29 23:52:14

8

我對我的CMS使用WordPress,所以大多數(如果不是全部)我的內部鏈接以「http」開頭。我發現這裏一個非常有趣的解決方案:http://www.focal55.com/blog/jquery-tutorial-add-class-all-outbound-links-your-site

如果該網站已關閉,它基本上可以歸結爲這個選擇(我修改了一點):

$('a[href^="//"],a[href^="http"]') 
    .not('[href*="' + window.location.hostname + '"]') 
; 

注意,這個選擇將not be the fastest根據jQuery文檔。

+0

這最終對我很好用 – Miva 2014-05-28 14:49:25

+0

很高興聽到它。請記住,可能會有一些邊緣情況會導致錯過外部鏈接。像external.com/?ref=internal.com這樣的東西可能會絆倒它。在我的使用中,我還沒有碰到過類似的東西,但它可能是很好的知道。 – 2014-06-20 18:25:04

1

我用這一個找到的所有URL指向domain other than current domain或具有(HTML5棄用)attribute target="_blank"

var contrastExternalLinks = function() { 
    //create a custom external selector for finding external links 
    $.expr[':'].external = function(obj) { 
     return (
      $(obj).attr('target') && $(obj).attr('target') =='_blank') 
       || 
        (!obj.href.match(/^mailto\:/) && !obj.href.match(/^tel\:/) && (obj.hostname != location.hostname) 
         ); 
    }; 
    // Usage: 
    $(document).ready(function() { 
     $('a:external').addClass('external');///css('background-color', 'green'); 
    }) 



}(); 
3

只能選擇重新指向您的域名如果href是完整的URL錨。

jQuery("a:not([href^='http://']), " + 
     "a[href^='http://localhost.com'], " + 
     "a:not([href^='http://localhost.com/wp-admin'])").addClass("internal"); 
3

我喜歡這個選擇我自己,它可以防止誤報爲指向網站(像那些通常由CMS系統生成的)絕對鏈接。

var currentDomain = document.location.protocol + '//' + document.location.hostname; 
var outboundLinks = 'a[href^="http"]:not([href*="' + currentDomain + '"])'; 

這裏的使用情況下這個工作對我來說,上下文:

var currentDomain = document.location.protocol + '//' + document.location.hostname; 
$('a[href^="http"]:not([href*="' + currentDomain + '"])').on('click', function (e) { 
    e.preventDefault(); 

    // track GA event for outbound links 
    if (typeof _gaq == "undefined") 
     return; 

    _gaq.push(["_trackEvent", "outbound", this.href, document.location.pathname + document.location.search]); 
}); 
0

我覺得這個簡單的少頭痛的方法是不使用純JavaScript或jQuery的,但結合它html代替,然後檢查包含您的基站網址的點擊鏈接。它將適用於任何類型的基本網址(例如:example.com,example.com/site)。如果您需要動態值,那麼您只需使用您喜歡的服務器端編程語言(如PHP,asp,java等)來設置該值。

下面是一個例子:

HTML

<!--Create a hidden input containing your base site's url.--> 
<input type="hidden" id="sitedomain" value="example.com/site"/> 

jQuery的

$(".elem").on("click", function(e){ 
    if($(this).closest("a").length) { 
    var url = $(this).attr("href"); 
    var sitedomain = $("#sitedomain").val(); 

    if(url.indexOf(sitedomain) > -1) { 
    alert("Internal"); 
    } else { 
    alert("External"); 
    } 
} 
}); 
0

嘗試

var fullBaseUrl = 'https://internal-link.com/blog'; 

var test_link1 = 'https://internal-link.com/blog/page1'; 
var test_link2 = 'https://internal-link.com/shop'; 
var test_link3 = 'https://google.com'; 

test_link1.split(fullBaseUrl)[0] == ''; // True 
test_link2.split(fullBaseUrl)[0] == ''; // False 
test_link3.split(fullBaseUrl)[0] == ''; // False 
+1

儘管這段代碼可能會回答這個問題,但提供關於**如何**和**爲什麼**的附加背景可以解決問題,這將提高答案的長期價值。 – Alexander 2018-02-03 15:30:32

0
$(document).ready(function() { 
$('a[href^="http"]').not('a[href^="http://' + $(location).attr('hostname') + 
'"]').attr('target', '_blank'); 
}); 

用「https」替換「http」如果您需要

相關問題