将 class 选择器与 nth-child() 或 eq() 组合

Combine the class selector with nth-child() or eq()

我有一个列表,我想获取每个标题项之后的第一项。我需要在一行中完成所有这些,因为我正在使用 Nightwatch,它没有在浏览器中使用 jquery 的所有弹性。我有的是:

// This works
console.log('first item after first header is ');
console.log($('#ul-wrapper li.heading ~ li:first').text());

// This doesnt
console.log('first item after second header is ');
console.log($('#ul-wrapper li.heading:nth-child(2) ~ li:first').text());

所以基本上我需要将 class 选择器与 nth-child() 或 eq() 结合起来。 Html 是:

<ul id="ul-wrapper">
   <li class="heading">

        Heading 1

   </li>
   <li>
      <label>
      <a>
        Item 1
      </a>
      </label>  
   </li>
   <li>
      <label>
      <a>
        Item 2
      </a>
      </label>  
   </li>
   <li class="heading">

        Heading 2

   </li>
   <li>
      <label>
      <a>
        Item 3
      </a>
      </label>  
   </li>
   <li>
      <label>
      <a>
        Item 4
      </a>
      </label>  
   </li>
</ul>

fiddle是here

I have a list and I want to get the first item after each heading item

如果我没看错你可以使用Adjacent sibling selectors

$('#ul-wrapper li.heading + li').css("background", "red");
.heading {
  background-color: lightgreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ul-wrapper" style="">
  <li class="heading">

    Heading 1

  </li>
  <li>
    <label>
      <a>
       Item 1
      </a>
    </label>
  </li>
  <li>
    <label>
      <a>
       Item 2
      </a>
    </label>
  </li>
  <li class="heading">

    Heading 2

  </li>
  <li>
    <label>
      <a>
       Item 3
      </a>
    </label>
  </li>
  <li>
    <label>
      <a>
       Item 4
      </a>
    </label>
  </li>
</ul>

:nth-child()伪class只看元素相对于父元素的索引。同样,:nth-of-type()只会根据类型查看元素的索引。 :nth-child()/:nth-of-type() 伪 classes 都不会考虑元素的 class 属性。

话虽如此,:eq() 方法将根据 过滤集 [= 的索引 select 一个元素42=](在这种情况下这正是您想要的)。然而,值得指出的是 :eq() 有一个从零开始的索引(不同于 :nth-child()/:nth-of-type())。在这种情况下,您需要使用 eq(1) 来访问第二个 li 元素:

Example Here

$('#ul-wrapper li.heading:eq(1) ~ li:first');

您也可以使用相邻兄弟组合器,+:

Example Here

$('#ul-wrapper li.heading:eq(1) + li');