jQuery 如果其 href 属性包含某些短语,则更改链接目标属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9459927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change link target attribute if its href attribute contains certain phrase
提问by FoxKllD
I am trying to check all anchors' tags using .each()
and set home URLs' target to _self
and other non-home URLs' target to _blank
.
我正在尝试使用检查所有锚点的标签.each()
并将主 URL 的目标设置为 ,_self
并将其他非主 URL 的目标设置为_blank
。
So far, I got this:
到目前为止,我得到了这个:
$('a').each(function() {
var homeURL = 'google.ca';
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
}
});
This is also on jsBin here.
这也是上jsBin这里。
For some reason, the non-home URLs set to target="_self"
. Can anyone explain why?
出于某种原因,非主 URL 设置为target="_self"
. 谁能解释为什么?
回答by Purag
Try this instead:
试试这个:
if($(this).is("[href*=" + homeURL + "]")){
$(this).attr('target','_self');
} else {
$(this).attr('target','_blank');
}
is()
returns true
if the selected element matches the selector in the function and false
if it does not. So, if the current link's href
attribute containsgoogle.ca
, it'll change its target
attribute to _self
. Otherwise, it'll set it to _blank
.
is()
true
如果所选元素与函数中的选择器匹配,则返回,如果不匹配false
。因此,如果当前链接的href
属性包含google.ca
,它会将其target
属性更改为_self
。否则,它会将其设置为_blank
.
And, in fact, for more efficiency, you should cache $(this)
:
而且,事实上,为了提高效率,您应该缓存$(this)
:
var $this = $(this);
if($this.is("[href*=" + homeURL + "]")){
$this.attr('target','_self');
} else {
$this.attr('target','_blank');
}
回答by charlietfl
var homeURL = 'google.ca';
$('a').each(function() {
$(this).attr('target', (this.href.match( homeURL )) ? '_self' :'_blank');
});
回答by fkoessler
You can also achieve this with:
您还可以通过以下方式实现:
$(document).ready(function() {
$("a[href^='http']").attr('target','_blank');
});