2017-08-17 55 views
1

如何将target=_blank属性添加到锚标记,除了按钮和某些div。如何不使用#添加目标属性到“呼叫控制”类和ID?将“target ='_blank'”添加到不包含给定ID的锚标记中

我已经试过这样:

$('a:not(.call-control,"#")').attr('target', '_blank').addClass('checkMate'); 
 

 
/* then later... */ 
 
$('.checkMate').attr("target", "");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="call-control"> 
 
    <span id="incomingCallBrand"></span> 
 
</div> 
 
<div> 
 
    <a href="#" class="comms-icon" id="iambusy"></a> 
 
    <span>Peter</span> 
 
</div>

+3

请包括您的HTML来帮助[演示问题](https://stackoverflow.com/help/mcve)。 – showdev

+0

1.将'target = _blank'添加到所有'a'标签中,包括'.call-control'和'#' ---------- 2.选择'.call-control'和'#'并删除'target = _blank'属性 – trgiangvp3

回答

0

无论你想选择什么样的具体环节,您的选择是无效的。

应用选择的任何链接,没有一定类,你正在寻找$("a:not('.class')")

应用选择到不具备一定的类中的任何链接 ,你正在寻找$("a:not('[href=#'])")

这些可以组合为$("a:not('.class-control, [href=#]')")

$("a:not('.call-control, [href=#]')").attr("target", "_blank").addClass('checkMate');
.checkMate { 
 
    color: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a class="call-control" href="#" rel="noopener noreferrer">Same Page (doesn't get the target)</a> 
 
<br /> 
 
<a class="call-control" href="http://www.google.com" rel="noopener noreferrer">Google (doesn't get the target)</a> 
 
<br /> 
 
<a href="http://www.facebook.com" rel="noopener noreferrer">Facebook (gets the target)</a>

另外,需要注意的是target=_blank有显著security vulnerability,可与window.opener()被利用是非常重要的。这可以是seen here。要解决此问题,您还需要将rel="noopener noreferrer"添加到您的链接(如上所述)。

希望这会有所帮助! :)

+0

我想排除名称为“”的类。呼叫控制“和一个标签谁没有href ='#' –

+0

@PrabinPoudel - 我已经更新了我的回答,以完全覆盖=] –

+0

谢谢@ bsidian-age,它可以正常工作,但我没有使用rel =“”字段,因为它在我的上下文中效率不高。 –

1

如果我理解正确的话,你要选择一个既没有类“呼叫控制”,也不是href设置为“元素#“,使用jQuery's .not()方法。

要选择无href组元素为 “#”,我建议jQuery's "Attribute Equals" Selector

.not([href=#]) 

添加等级要求:

.not([href=#],.call-control) 

我还建议removeAttr()而不是在target设置为空白字符串。

下面是一个例子:

$('a:not([href=#],.call-control)').attr('target', '_blank').addClass('checkMate'); 
 

 
/* remove the attribute after one second */ 
 
setTimeout(function(){ 
 
    $('.checkMate').removeAttr('target'); 
 
},1000);
a { 
 
    display: block; 
 
} 
 

 
.checkMate { 
 
    background-color:pink; 
 
} 
 

 
/* to demonstrate when the target has been removed */ 
 
a[target=_blank] { 
 
    background-color:lightgreen; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<a href="#" class="call-control">Class and HREF</a> 
 
<a href="page.html" class="call-control">Just Class</a> 
 
<a href="#">Just HREF</a> 
 
<a href="http://example.com">Neither Class nor HREF</a>

参考:
Add a class to a href that's set to '#'

相关问题