jQuery:选择 X 类中与该类没有 sibling 的元素

标签 jquery jquery-selectors

我只想选择与 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/

相关文章:

javascript - 保留 html 片段还是仅使用 javascript 构建?

javascript - jquery ui 中的位置()

javascript - 从客户端填充 IFRAME

jquery 在类中选择元素

javascript - 如何找到包含精确文本字符串的特定类的跨度?

jQuery 获取选择器值帮助

javascript - 每 10 tr 使用 10n jquery

php - 结合 jQuery 和 Zen-Coding php 端口以在服务器端脚本上模拟客户端编程风格

javascript - 为什么 jquery/javascript 代码会与其他 jquery/javascript 发生冲突?

jquery:删除基于属性数组和其他选择框选择的选择选项