如何将target=_blank属性添加到锚标记,但按钮和某些div除外。我如何不添加目标属性到“调用控制”类和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>
发布于 2017-08-17 00:46:31
无论您试图选择哪些特定链接,选择器都是无效的。
要将所选内容应用于没有特定类的任何链接,您需要查找$("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有一个重要的安全漏洞,它可以被window.opener()利用。这可以是在这里看到的。要解决这个问题,还需要将rel="noopener noreferrer"添加到您的链接中(如上面所示)。
希望这会有帮助!)
发布于 2017-08-17 00:42:56
如果我正确理解,您希望使用href方法选择一个既没有类“调用控制”也没有将href设置为"#“的元素。
要选择没有将href设置为"#“的元素,我建议使用jQuery的“属性等于”选择器
.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>
供参考:
https://stackoverflow.com/questions/45724909
复制相似问题