Fox*_*llD 5 jquery if-statement target jquery-selectors
我正在尝试检查所有锚点的标签.each()
,并将主页URL的目标设置为_self
和其他非主页URL的目标_blank
.
到目前为止,我得到了这个:
$('a').each(function() {
var homeURL = 'google.ca';
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
}
});
Run Code Online (Sandbox Code Playgroud)
这也是jsBin 在这里.
出于某种原因,非主页URL设置为target="_self"
.有谁能解释为什么?
试试这个:
if($(this).is("[href*=" + homeURL + "]")){
$(this).attr('target','_self');
} else {
$(this).attr('target','_blank');
}
Run Code Online (Sandbox Code Playgroud)
is()
true
如果所选元素与函数中的选择器匹配,则返回,如果不匹配则返回false
.因此,如果当前链接的href
属性包含 google.ca
,它将其target
属性更改为_self
.否则,它会将其设置为_blank
.
而且,实际上,为了提高效率,您应该缓存$(this)
:
var $this = $(this);
if($this.is("[href*=" + homeURL + "]")){
$this.attr('target','_self');
} else {
$this.attr('target','_blank');
}
Run Code Online (Sandbox Code Playgroud)
var homeURL = 'google.ca';
$('a').each(function() {
$(this).attr('target', (this.href.match( homeURL )) ? '_self' :'_blank');
});
Run Code Online (Sandbox Code Playgroud)