使用jQuery检查链接是内部链接还是外部链接
我想写一个脚本,可以确定链接是内部的还是外部的。从我的角度来看,这很简单,所有的内部链接都是相对的,所以它们以/开头。所有外部链接都以http://-开始,到目前为止一切正常。但是,我不知道如何对文本以外的任何对象执行“:contains()”—如何在属性中搜索字符串 一旦我能做到这一点,我很乐意自己添加target _blank,除非您知道更好的方法您可以使用语法查找以使用jQuery检查链接是内部链接还是外部链接,jquery,Jquery,我想写一个脚本,可以确定链接是内部的还是外部的。从我的角度来看,这很简单,所有的内部链接都是相对的,所以它们以/开头。所有外部链接都以http://-开始,到目前为止一切正常。但是,我不知道如何对文本以外的任何对象执行“:contains()”—如何在属性中搜索字符串 一旦我能做到这一点,我很乐意自己添加target _blank,除非您知道更好的方法您可以使用语法查找以http或/开头的HREF: $("a[href^='http']") // external $("a[href^='/'
http
或/
开头的HREF:
$("a[href^='http']") // external
$("a[href^='/']") // internal
这里有一个更好的解决方案:您可以使用下面的插件代码向jQuery添加
$('a:external')
和$('a:internal')
选择器。任何以http://、https://
或任何内容开头的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);
};
我使用WordPress作为我的CMS,所以我的大部分(如果不是全部的话)内部链接都以“http”开头。我在这里找到了一个非常有趣的解决方案:
如果站点关闭,它基本上可以归结为这个选择器(我对它做了一些修改):
请注意,此选择器将根据jQuery文档进行选择。我使用此选择器查找指向当前域以外的域的所有URL
或具有(html5已弃用)属性target=“\u blank”
当href是完整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;
$('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]);
});
我认为简单且不那么麻烦的方法不是使用纯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"/>
试试看
如果需要,请将“http”替换为“https”我说的内部url不总是以正斜杠开头,对吗。在内部使用$('a[href!=http:]a[href!=https:')可能更好。对于我正在做的事情,属性选择器是更好的选择。然而,它们有一个小问题。它们应该是$('a[href^=“http”]”和$('a[href^=“/”])这将使用协议相关URL失败,例如//www.google.com
。您可以使用/^(\w+:)?\/\/
@landon好主意。好了,很高兴听到这个消息。请记住,在某些边缘情况下,可能会丢失外部链接。像external.com/?ref=internal.com这样的东西可能会使它出错。在我的使用过程中,我还没有遇到过类似的情况,但知道这一点可能会很好。虽然这段代码可能会回答这个问题,但提供关于它如何以及为什么解决这个问题的附加上下文将提高答案的长期价值。
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]);
});
<!--Create a hidden input containing your base site's url.-->
<input type="hidden" id="sitedomain" value="example.com/site"/>
$(".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');
});