gpt4 book ai didi

jquery-selectors - 如果其 href 属性包含特定短语,则更改链接目标属性

转载 作者:行者123 更新时间:2023-12-03 22:55:21 25 4
gpt4 key购买 nike

我正在尝试使用 .each() 检查所有 anchor 的标签,并将主页 URL 的目标设置为 _self 并将其他非主页 URL 的目标设置为 _blank

到目前为止,我得到了这个:

$('a').each(function() {
var homeURL = 'google.ca';
if ( $(this+'[href*='+homeURL+']')) {
$(this).attr('target','_self');
}else{
$(this).attr('target','_blank');
}
});

这也在 jsBin here 上.

由于某种原因,非主页网址设置为 target="_self"。谁能解释一下为什么吗?

最佳答案

试试这个:

if($(this).is("[href*=" + homeURL + "]")){
$(this).attr('target','_self');
} else {
$(this).attr('target','_blank');
}

is()如果所选元素与函数中的选择器匹配,则返回 true;如果不匹配,则返回 false。因此,如果当前链接的 href attribute contains google.ca,它会将其 target 属性更改为 _self。否则,它会将其设置为_blank

事实上,为了提高效率,您应该缓存 $(this):

var $this = $(this);
if($this.is("[href*=" + homeURL + "]")){
$this.attr('target','_self');
} else {
$this.attr('target','_blank');
}

关于jquery-selectors - 如果其 href 属性包含特定短语,则更改链接目标属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9459927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com