How do I test to see if links are external or internal? Please note:
- 我无法硬编码本地域.
- 我无法测试"http".我可以很容易地通过http绝对链接链接到我自己的站点.
- I want to use jQuery / javascript, not css.
我怀疑答案就在某个地方.href,但我没有找到解决方案.
Thanks!
How do I test to see if links are external or internal? Please note:
我怀疑答案就在某个地方.href,但我没有找到解决方案.
Thanks!
var comp = new RegExp(location.host);
$('a').each(function(){
if(comp.test($(this).attr('href'))){
// a link that contains the current host
$(this).addClass('local');
}
else{
// a link that does not contain the current host
$(this).addClass('external');
}
});
注意:这只是一个快速的&;肮脏的例子.它将匹配所有href="#anchor"链接
Update 2016-11-17
这个问题仍然有很多流量,很多人都告诉我,这个公认的解决方案会在好几次失败.正如我所说,这是一个非常快速和肮脏的答案,以显示如何解决这个问题的主要方法.更复杂的解决方案是使用<a>
(锚定)元素上可访问的属性.正如@Daved在这个答案中已经指出的,关键是将hostname
与当前的window.location.hostname
进行比较.我更倾向于比较hostname
个属性,因为如果port
个属性与80个属性不同,它们永远不包括host
个属性.
现在我们开始:
$( 'a' ).each(function() {
if( location.hostname === this.hostname || !this.hostname.length ) {
$(this).addClass('local');
} else {
$(this).addClass('external');
}
});
State of the art:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});