2009-08-04 97 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”如果您需要

相关问题