2014-01-06 60 views
2

比方說,我有以下設置:jQuery選擇和sibblings

<div> 
<div class="pr-selec">some text</div> 
... 
</div> 


<div> 
<div class="pr-selec">some text</div> 
<div class="new-class">other text</div> 
... 
</div> 

使用jQuery,我怎麼可以只選擇沒有sibbiling .new-class DIV的.pr-selec的div類?

我是想這樣的事情:

jQuery(".pr-selec").not().sibblings("new-class").each({ 
      //stuff 
     }); 

但並沒有這樣做。

回答

3

您使用filter更好:

jQuery(".pr-selec").filter(function(){ 
    return !$(this).siblings('.new-class').length; 
}).each(...) 
+0

輝煌。謝謝! – thindery

4

嘗試.not():has-selectornext-sibling selector

$('.pr-selec').not(':has(~ .new-class)').css('color', 'red') 

演示:Fiddle

注:如果new-class元素不是這樣可不行下一個兄弟姐妹(前一個):Fiddle

+0

+1很好解釋 – lhan

+0

真的很喜歡這個解決方案。謝謝。在我的情況下,「新類」總是下一個s 012 – thindery

+0

這非常聰明! +1,但正如你所說,它只對下一個元素有效,比'filter'慢:http://jsperf.com/test-siblings –