单击操作后存在具有特定类的计数元素

k3bvogb1  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(254)

我有两个“大厅”和一个隐藏大厅的链接。单击后,我想计算有多少个元素 machine-on 存在。我尝试了以下方法,但不起作用。。有什么想法吗?
例如,当我单击“隐藏大厅1”时,计数器应返回1。

$('.hide-hall').click(function() {

  $(this).closest('.hall').addClass('d-none');

  var counterOn = 0;
  $('.hall :not(.d-none)').children('.btn').each(function() {
    if ($(this).hasClass('machine-on')) {
      counterOn++;
    }
  });

  console.log("counterOn = " + counterOn);

});
.d-none {
  display: none;
}

.machine-on {
  color: blue;
}

.machine-off {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="hall">
  <p> HALL 1 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 1</span>
  <span class="btn machine-on">Machine 2</span>
  <span class="btn machine-off">Machine 3</span>
</div>
<br/><br/>
<div class="hall">
  <p> HALL 2 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 4</span>
</div>
laawzig2

laawzig21#

通过选择“全部”,可以更轻松地计算元素 .hall 那是 .not.d-none 数一数 .find('.machine-on') 使用 .length .

$('.hide-hall').click(function() {
  $(this).closest('.hall').addClass('d-none');

  console.log($('.hall').not('.d-none').find('.machine-on').length);
});
.d-none {
  display: none;
}

.machine-on {
  color: blue;
}

.machine-off {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="hall">
  <p> HALL 1 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 1</span>
  <span class="btn machine-on">Machine 2</span>
  <span class="btn machine-off">Machine 3</span>
</div>
<br/><br/>
<div class="hall">
  <p> HALL 2 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 4</span>
</div>
qpgpyjmq

qpgpyjmq2#

前面的空间 :not 导致这不起作用。

$('.hall:not(.d-none)').children('.btn').each(function() {

完整代码:

$('.hide-hall').click(function() {

  $(this).closest('.hall').addClass('d-none');

  var counterOn = 0;
  $('.hall:not(.d-none)').children('.btn').each(function() {
    if ($(this).hasClass('machine-on')) {
      counterOn++;
    }
  });

  console.log("counterOn = " + counterOn);

});
.d-none {
  display: none;
}

.machine-on {
  color: blue;
}

.machine-off {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="hall">
  <p> HALL 1 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 1</span>
  <span class="btn machine-on">Machine 2</span>
  <span class="btn machine-off">Machine 3</span>
</div>
<br/><br/>
<div class="hall">
  <p> HALL 2 <a href="#" class="hide-hall" title="Hide hall">Hide</a></p>
  <span class="btn machine-on">Machine 4</span>
</div>

相关问题