我有像
这样的html结构<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>
如何让所有元素都包含a或b或c类
$(".dv").each(function(){}); /// ? how to get
如何让所有元素都不包含a或b类
$(".dv:not(.a|.b)").each(function() {}); // ?how to get
答案 0 :(得分:5)
使用or
逻辑选择:
$( ".a, .b, .c" )
使用not
逻辑选择:
$( "div:not(.a, .b)" )
选择所有.dv
但不选择.d
:
$( ".dv:not(.d)" )
这是一个使用上述选择器计算所有逻辑的代码段:
var orCount = $( ".a, .b, .c" ).length;
var andCount = $( "div:not(.a, .b)" ).length;
var notdCount = $( ".dv:not(.d)" ).length;
console.log('or logic count = ' + orCount);
console.log('and logic count = ' + andCount);
console.log('not d logic count = ' + notdCount);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>
&#13;
答案 1 :(得分:2)
关于jQuery的事情是它可以利用你的CSS技能,只要浏览器是最新的。如果是,那么以下纯CSS选择器将完成这项工作:
.dv.a, .dv.b, .dv.c { /* Matching Ones: */
}
.dv:not(.a):not(.b):not(.c) { /* Non Matching Ones: */
}
以下代码段将说明这一点:
.dv.a, .dv.b, .dv.c {
color: red;
}
.dv:not(.a):not(.b):not(.c) {
border: thin solid green;
}
<div class="dv a">a</div>
<div class="dv a">a1</div>
<div class="dv b">b</div>
<div class="dv b">b1</div>
<div class="dv c">c</div>
<div class="dv c">c1</div>
<div class="dv d">d</div>
<div class="dv d">d1</div>