我想编写一个脚本,可以确定链接是内部链接还是外部链接。在我看来,这很简单,所有的内部链接都是相对路径,所以它们以 / 开头。所有的外部链接都以 http:// 开头 - 到目前为止都很好。但是,我无法弄清如何对除文本以外的任何属性执行“:contains()”操作 - 如何在属性中搜索字符串?
一旦我能够做到这一点,我就可以自己添加 target _blank,除非您知道更好的方法。
我想编写一个脚本,可以确定链接是内部链接还是外部链接。在我看来,这很简单,所有的内部链接都是相对路径,所以它们以 / 开头。所有的外部链接都以 http:// 开头 - 到目前为止都很好。但是,我无法弄清如何对除文本以外的任何属性执行“:contains()”操作 - 如何在属性中搜索字符串?
一旦我能够做到这一点,我就可以自己添加 target _blank,除非您知道更好的方法。
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);
};
我正在使用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文档,这个选择器不是最快的。
当 href 是 完整的 URL 时,只选择指向您的域的锚点。
jQuery("a:not([href^='http://']), " +
"a[href^='http://localhost.com'], " +
"a:not([href^='http://localhost.com/wp-admin'])").addClass("internal");
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]);
});
$(document).ready( function() {
$('a[href^="http"]').not('a[href^="http://' + $(location).attr('hostname') +
'"]').attr('target', '_blank');
});
除当前域之外的域名
或带有(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');
})
}();
试一下
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
我认为这个问题的简单且不会出错的方法是不要使用纯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");
}
}
});
//www.google.com
),这将失败。 - LandonSchropp/^(\w+:)?\/\//
来修复它。 - LandonSchropp