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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:50:24  来源:igfitidea点击:

Change link target attribute if its href attribute contains certain phrase

jquery-selectorsif-statementtargetjquery

提问by FoxKllD

I am trying to check all anchors' tags using .each()and set home URLs' target to _selfand 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 trueif the selected element matches the selector in the function and falseif it does not. So, if the current link's hrefattribute containsgoogle.ca, it'll change its targetattribute 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');
});