我只想选择与 X 类匹配的元素,并且没有任何同级也具有 X 类的元素。在我的例子中,X = hasDatepicker
。这是我想到的:
$('.hasDatepicker:not(.hasDatepicker ~ .hasDatepicker)')
但是,这并不排除第一个元素,因此在任何日期选择器组中,这仍然会选择第一个元素。我不想包含任何团体成员,只包含单例成员。
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>
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>
有什么想法吗?谢谢!
最佳答案
它不是那么优雅,但它使用:first-child来实现这一点。伪选择器并使用 .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
});
<强> DEMO
关于jQuery:选择 X 类中与该类没有 sibling 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10146136/