2012-04-13 189 views
10

我想只選擇與類X匹配的元素,並且沒有的任何也具有類X的兄弟。在我的示例中,X = hasDatepicker。這是我想出來的:jQuery:選擇沒有該類的兄弟的類X的元素

$('.hasDatepicker:not(.hasDatepicker ~ .hasDatepicker)') 

然而,這並不排除第一要素,所以在任何一組datepickers的,這仍然會選擇第一個。我不想包括任何組中的任何人,只有單身。

實施例與匹配度:

<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> 

實施例與相配:

<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> 

任何想法?謝謝!

+1

你能提供的HTML結構,哪些是你想匹配的元素的例子嗎? – 2012-04-13 18:27:25

+0

@GaryGreen完成:) – Garrett 2012-04-13 18:35:07

+0

那麼你希望基於你的例子,父div或hasDatepicker類的輸入選擇什麼元素? – j08691 2012-04-13 18:41:01

回答

8

這不是優雅,但它使用:first-child僞選擇和過濾結果與.filter()設置的伎倆:

  • :first-child將有助於只選擇一個可能的多個兄弟姐妹的第一。測試元素名單

  • 使用.filter()實際檢查是否有與同一類

沒有兄弟姐妹

下面的代碼:

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

DEMO

+3

返回'!$(this).siblings('。text').length'而不是 – ori 2012-04-13 18:30:02

+0

它確實很適合使用.siblings()。謝謝 ! – 2012-04-13 18:31:34

+0

不確定這是否是一個問題,但如果有其他元素是第一個兄弟元素,這將不起作用。如果這是一個問題,只要刪除':first-child'部分。 – 2012-04-13 18:52:31