jQuery:选择X类中没有该类兄弟的元素

Gar*_*ett 10 jquery jquery-selectors

我只想选择与X类匹配的元素,并且没有任何同类X的兄弟.在我的情况下,X = hasDatepicker.这是我想出的:

$('.hasDatepicker:not(.hasDatepicker ~ .hasDatepicker)')
Run Code Online (Sandbox Code Playgroud)

但是,这并不排除第一个元素,所以在任何一组日期选择器中,这仍然会选择第一个元素.我不想包括任何一组,只包括单曲.

1匹配示例:

<div class="input text">
<input name="data[Goal][date_started]" type="text" value="" class="hasDatepicker" style="display: none; ">
<button type="button" class="ui-datepicker-trigger"><img src="/themed/mocha/images/btn_calendar.png" alt="..." title="..."></button>
</div>
Run Code Online (Sandbox Code Playgroud)

0匹配示例:

<div class="input text">
<input type="text" value="" id="GoalDateStarted" class="hasDatepicker"><input type="text" value="" class="hasDatepicker" style="display: none; ">
<input type="text" value="" class="hasDatepicker" style="display: none; ">
<input name="data[Goal][date_started]" type="text" value="" class="hasDatepicker" style="display: none; ">
<button type="button" class="ui-datepicker-trigger"><img src="/themed/mocha/images/btn_calendar.png" alt="..." title="..."></button>
</div>
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢!

Did*_*hys 8

这不是优雅,但它使用的伎俩:第一胎伪选择和过滤结果设定.filter() :

  • :first-child 将帮助仅选择可能的多个兄弟列表中的第一个.test元素

  • .filter()实际检查是否有与相同类别中没有兄弟姐妹

这是代码:

var a = $('.test:first-child').filter(function() {
    //return $(this).parent().find('.test').not(this).length == 0;
    return !$(this).siblings('.test').length
});
Run Code Online (Sandbox Code Playgroud)

DEMO

  • 返回`!$(this).siblings('.text').length`而不是 (3认同)