选择具有确切类别组合的元素

时间:2019-04-12 19:23:00

标签: javascript jquery

我已经以某种方式在this post问了这个问题,但是结果是我在寻找错误的解决方案!我的坏人!

如您所见,我正在寻找一种解决方案,以显示具有数组值组合的div。例如,在此演示中,输出为3个div,分别为Has QHas MHas Q & M ,我只需要显示Has Q & M在div中具有数组元素的所有组合

$('.A.W.B').css("background-color", "red");
let mopt = ['Q','M'];

$('.box').not(
  mopt.map(function(className){ return '.'+ className; }).join(', ')
).hide();
.box {
  height: 20px;
  background: khaki;
  width: 100px;
  text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4> Should Display Only the Div which Has 'Q' <strong>AND </strong> 'M' together</h4>

<div class="box A B F  R W Q">Has Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R">No Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R M">Has M</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B Q F H  M K F">Has Q & M</div>

<p> but it is displaying all boxes which have part of `mopt` array</p>

2 个答案:

答案 0 :(得分:3)

当使用逗号分隔选择器时,它将充当multiple selectors,表示它们每个都充当选择器。将它们连接在一起,没有任何空间。

$('.A.W.B').css("background-color", "red");
let mopt = ['Q','M'];

$('.box').not(
  mopt.map(function(className){ return '.'+ className; }).join('')
).hide();
.box {
  height: 20px;
  background: khaki;
  width: 100px;
  text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4> Should Display Only the Div which Has 'Q' <strong>AND </strong> 'M' together</h4>

<div class="box A B F  R W Q">Has Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R">No Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R M">Has M</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B Q F H  M K F">Has Q & M</div>

<p> but it is displaying all boxes which have part of `mopt` array</p>

引用:

Selecting Elements | JQuery

Simple Selectors | MDN

答案 1 :(得分:1)

选择器的工作方式是,您需要使用与.关联的类名才能包含多个类。因此,对于此示例,您将需要.Q.M

您可以通过以下方式完成此操作

'.' + mopt.join('.')

如下所示

$('.A.W.B').css("background-color", "red");
let mopt = ['Q','M'];

$('.box').not(
  '.' + mopt.join('.')
).hide();
.box {
  height: 20px;
  background: khaki;
  width: 100px;
  text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4> Should Display Only the Div which Has 'Q' <strong>AND </strong> 'M' together</h4>

<div class="box A B F  R W Q">Has Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R">No Q</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B F W R M">Has M</div>
<div class="box A B F H K F">No Q</div>
<div class="box A B Q F H  M K F">Has Q & M</div>

<p> but it is displaying all boxes which have part of `mopt` array</p>