2012-10-18 44 views
11

我需要.closest().parents()之間的功能。我正在向某個父母的某個元素的所有父母申請一些CSS。現在我while循環,但似乎有更好的方法來做到這一點。如何獲得所有父母,直到達到某個父母

var goUp = $(".distant-child"); 
while(!goUp.hasClass("ancestor-to-stop-at")){ 
    goUp.css("height","100%"); 
    goUp = goUp.parent(); 
} 

我寧願做這樣的事情的其中之一:

$(".distant-child").closest(".ancestor-to-stop-at").css("height","100%"); //won't work because .closest() only returns the top ancestor 
$(".distant-child").parents(".ancestor-to-stop-at").css("height","100%"); //won't work because .parents() doesn't take this parameter and won't stop at the specified element. 

我怎樣才能做到這一點沒有while循環?

+0

您是否在尋找http://api.jquery.com/parentsUntil/? –

+0

*磨損鞋污垢* ...是的... – brentonstrine

+0

當您使用JavaScript直接與CSS混用時,它通常被認爲是*代碼氣味*(除非您正在做動畫)。 –

回答

22

您可以使用jQuery parentsUntil()功能

$(".distant-child").parentsUntil(".ancestor-to-stop-at").css("height","100%"); 
+35

...我是個白癡。 – brentonstrine

+17

@brentonstrine:當你的「我是白癡」評論時,這個尷尬的時刻會比答案本身得到更多的讚揚。 –

+0

@MadaraUchiha:是的,但如果那些upvoters像我一樣,那麼他們可能有完全相同的「我是白癡」的感覺;-) –