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

我想写一个脚本,可以确定链接是内部链接还是外部链接。 从我的角度来看这很简单,所有内部链接都是相对的,所以它们以/开头。 所有外部链接都以http://开头 – 到目前为止一切都很好。 但是我无法弄清楚如何在除文本之外的任何内容上执行’:contains()’ – 如何在属性中搜索字符串?

一旦我能做到这一点,我很乐意自己添加target _blank,除非你知道更好的方法

您可以使用attribute^=value语法来查找以http/开头的href:

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

这是一个更好的解决方案:您可以使用下面的插件代码将$('a:external')$('a:internal')选择器添加到jQuery。 任何以http://https://whatever://开头的URL whatever://被视为外部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); }; 

我正在为我的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 + '"]' ) ; 

请注意,根据jQuery文档,此选择器不会是最快的 。

当href为FULL URL时,仅选择指向域的锚点。

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

我自己更喜欢这个选择器,它可以防止指向您网站的绝对链接的误报(就像那些通常由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]); }); 

我使用这个来查找指向domain other than current domain所有URL或者使用(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'); }) }(); 

我认为简单且不那么头痛的方法不是使用纯javascript或jQuery,而是将其与html结合使用,然后检查包含基本站点url的点击链接。 它适用于任何类型的基本URL(例如:example.com,example.com / sites)。 如果需要动态值,那么只需使用首选的服务器端编程语言设置值,例如PHP,asp,java等。

这是一个例子:

HTML

   

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

试试吧

 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 
 $(document).ready( function() { $('a[href^="http"]').not('a[href^="http://' + $(location).attr('hostname') + '"]').attr('target', '_blank'); }); 

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