jQuery:如何检查孩子是第一个也是最后一个

the*_*dnp 4 jquery css-selectors

我正在尝试为元素设置自定义样式

  • ul - 许多孩子中的第一个(ul.first)
  • 最后一个孩子(ul.last)
  • 唯一的孩子(ul.first.last或ul.only)

HTML:

<ul class="selector">
    <li class="selector">some li
       <ul class="">
          <li>some fancy li - the ul parent should have first class</li>
       </ul>
       <ul class="">
          <li>some more li - the ul parent should have last class</li>
       </ul>
    </li>
    <li class="selector">some second li
        <ul class="">
          <li>some lonely li - the ul parent should have first and last classes</li>
       </ul>
    </li>
</ul>
Run Code Online (Sandbox Code Playgroud)

所以我提出了一个希望做到这一点的jQuery

$('ul.selector li.selector > ul').each(function () {
  if ($(this).is(':first') && $(this).is(':last')) {
    $(this).addClass('first last');
  } else if ($(this).is(':first')) {
    $(this).addClass('first');
  } else if ($(this).is(':last')) {
    $(this).addClass('last');
  }
});
Run Code Online (Sandbox Code Playgroud)

谢谢你的任何建议.

更新 - 这是一个你可以玩的小提琴,基于其中一个答案:http://jsfiddle.net/qAtpe/

Man*_*eUK 10

为什么不这样:

$('ul.selector li.selector > ul').each(function() {
    $this = $(this); // cache $(this)
    if ($this.is(':first')) {
        $this.addClass('first'); 
    } 
    if ($this.is(':last')) {
        $this.addClass('last'); 
    }
});
Run Code Online (Sandbox Code Playgroud)

然后使用以下CSS

.first {
    //this is first
}
.last { 
    // this is last
}
.first.last {
    // this is first and last - ie the only child
}
Run Code Online (Sandbox Code Playgroud)

更新

$('ul.selector li.selector > ul').each(function() {
    $this = $(this); // cache $(this)
    if ($this.is(':first-child')) {
        $this.addClass('first'); 
    } 
    if ($this.is(':last-child')) {
        $this.addClass('last'); 
    }
});
?
Run Code Online (Sandbox Code Playgroud)

看看你的例子jsfiddle - 你需要选择器:first-child而不是:first......

:第一个伪类相当于:eq(0).它也可以写成:lt(1).虽然这只匹配一个元素,但是:first-child可以匹配多个:每个父元素一个.

这现在有效:

工作实例