使用jQuery / javascript测试链接是否在外部? [英] Test if links are external with jQuery / javascript?
问题描述
如何测试链接是外部链接还是内部链接?请注意:
How do I test to see if links are external or internal? Please note:
- 我无法对本地域进行硬编码。
- 我无法测试http 。我可以通过http绝对链接轻松链接到我自己的网站。
- 我想使用jQuery / javascript,而不是css。
我怀疑答案位于location.href的某个地方,但解决方案避开了我。
I suspect the answer lies somewhere in location.href, but the solution evades me.
谢谢!
推荐答案
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链接
作为外部。可以通过进行一些额外的RegExp检查来改善。
Note: this is just a quick & dirty example. It would match all href="#anchor" links as external too. It might be improved by doing some extra RegExp checking.
更新2016-11-17
这个问题仍然有很多流量,很多人告诉我这个接受的解决方案会在几次失败。正如我所说,这是一个非常快速和肮脏的答案,以显示如何解决这个问题的主要方式。更复杂的解决方案是使用可在< a>
(锚点)元素上访问的属性。就像@Daved在这个答案中已经指出的那样,关键是将主机名
与当前的 window.location.hostname
。我更愿意比较主机名
属性,因为它们从不包含包含在<$ c $中的
属性如果它与80不同。端口
c> host
This question still got a lot of traffic and I was told by a ton of people that this accepted solution will fail on several occasions. As I stated, this was a very quick and dirty answer to show the principal way how to solve this problem. A more sophisticated solution is to use the properties which are accessible on a <a>
(anchor) element. Like @Daved already pointed out in this answer, the key is to compare the hostname
with the current window.location.hostname
. I would prefer to compare the hostname
properties, because they never include the port
which is included to the host
property if it differs from 80.
所以我们走了:
$( 'a' ).each(function() {
if( location.hostname === this.hostname || !this.hostname.length ) {
$(this).addClass('local');
} else {
$(this).addClass('external');
}
});
最新技术:
Array.from( document.querySelectorAll( 'a' ) ).forEach( a => {
a.classList.add( location.hostname === a.hostname || !a.hostname.length ? 'local' : 'external' );
});
这篇关于使用jQuery / javascript测试链接是否在外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!