我想获取具有类assigned-names但没有名为hidden的类的span标签的数量。以下是HTML代码:

<div class="assigned-values">
    <span class="assigned-names">
          <span class="name">Test 1</span>
    </span>
    <span class="assigned-names hidden">
          <span class="name">Test 2</span>
    </span>
    <span class="assigned-names hidden">
          <span class="name">Test 3</span>
    </span>
</div>


因此,对于上述HTML,具有类assigned-names但没有类hidden的span标签的数量为1。

我试过下面的代码,但它的长度为2:

$('.assigned-values').find('span.assigned-names:not(:has(.hidden))').length

最佳答案

您可以使用not()函数简单地过滤掉不需要的元素:



const elems = $(".assigned-values > .assigned-names").not(".hidden");
console.log(elems.length);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="assigned-values">
  <span class="assigned-names">
          <span class="name">Test 1</span>
  </span>
  <span class="assigned-names hidden">
          <span class="name">Test 2</span>
  </span>
  <span class="assigned-names hidden">
          <span class="name">Test 3</span>
  </span>
</div>

关于javascript - jQUERY:计数没有类的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50753280/

10-09 23:29