使用jQuery检查链接是内部链接还是外部链接

14

我想编写一个脚本,可以确定链接是内部链接还是外部链接。在我看来,这很简单,所有的内部链接都是相对路径,所以它们以 / 开头。所有的外部链接都以 http:// 开头 - 到目前为止都很好。但是,我无法弄清如何对除文本以外的任何属性执行“:contains()”操作 - 如何在属性中搜索字符串?

一旦我能够做到这一点,我就可以自己添加 target _blank,除非您知道更好的方法。

8个回答

26
你可以使用 attribute^=value 语法来查找以 http/ 开头的 hrefs:
$("a[href^='http']") // external
 
$("a[href^='/']") // internal

以下是更好的解决方案:你可以使用以下插件代码在jQuery中添加$('a:external')$('a:internal')选择器。任何以http://https://whatever:////开头的URL都被视为外部链接。所有其他URL都被视为内部链接。

    $.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);
    };

9
我说的对吗,内部URL并不总是以斜杠开头。使用$('a[href!=http:] a[href!=https:]')来表示内部链接可能更好。 - kim3er
对于我所做的事情,属性选择器是更好的选择。然而,它们存在一个小问题。它们应该是$('a[href^="http"]')和$('a[href^="/"]')。 - Tony
3
如果使用协议相对 URL(例如//www.google.com),这将失败。 - LandonSchropp
2
你可以使用/^(\w+:)?\/\//来修复它。 - LandonSchropp
@landon 好主意。完成了。 - Patrick McElhaney
错误答案。在以“//”开头的链接和以页面名称而不是“/”开头的内部链接处失败。 - Toolkit

10

我正在使用WordPress作为我的CMS,因此我内部的大多数(如果不是全部)链接都以"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 + '"]' )
;

请注意,根据jQuery文档,这个选择器不是最快的


很高兴听到这个消息。请记住,在某些边缘情况下,它可能会错过外部链接。例如 external.com/?ref=internal.com 可能会导致其失效。在我的使用中还没有遇到过类似的情况,但了解这一点可能是有好处的。 - Dominic P

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]);
});

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

如果需要,将“http”替换为“https”。

1
我使用这个来查找指向除当前域之外的域名或带有(HTML5不推荐使用的)属性target="_blank"的所有URL。
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');   
    })



}();

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

0

我认为这个问题的简单且不会出错的方法是不要使用纯JavaScript或jQuery,而是将其与HTML结合起来,然后检查所点击的链接是否包含您的基本站点URL。它适用于任何类型的基本URL(例如: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");
  }
 }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接