我需要选择所有的a
标记,但它们不应该在第一个子级中有标记img
。
我为它编写了脚本,但省略了选择器。
$(document).ready(function() {
$().mouseenter(function(i) {
$(this).css("border","2px solid orange");
}).mouseleave(function(i){
$(this).css("border","none");
});
});
和HTML:
<a href=""></a><!--need to select-->
<a href=""><!--don't need to select-->
<img src"">
</a>
<a href=""></a><!--need to select-->
选择器为:
$("a:not(:has(img))")
它将选择所有不包含img
的a
元素。
演示
$("a").not("a>img")
这比mishik的答案读起来更清楚,但也更慢。不过这应该不是问题。
根据jQuery文档:
.not()方法最终将为您提供更可读的选择,而不是将复杂的选择器或变量推入:not()选择器过滤器。在大多数情况下,这是一个更好的选择。
将集合构建为选择器:
var $anchors = $("a");
var $containsImg = $("a").children("img").parent();
$anchors.not( $containsImg );
较短的形式:
var $anchors = $("a");
$anchors.not( $anchors.children("img").parent() );
另一种方法:检查链接是否包含处理程序中的图像:
$("a").mouseenter(function(){
if ( $(this).children("img").length == 0 ){
$(this).css("border", "2px solid orange");
}
}).mouseleave(function(){
if ( $(this).children("img").length == 0 ){
$(this).css("border", "none");
}
});
行为略有不同:由于检查是动态完成的,这也适用于在页面加载后接收图像的锚点(例如:$anchor.append('<img src="..." />');
)