2012-06-15 37 views
1

我不能直接使用$('commentbody'),因爲有很多註釋和選擇需要完成這個特定的區域。無法到達層次結構中的特定元素

HTML:

<div class="commentline"> 
    <div class="carrowholder"> 
     <div class="ctoggle"></div> 
     <div class="arrowwrap"> 
     </div> 
    </div> 
    <div class="commentholder"> 
     <div class="commenttitle"> 
      Title 
     </div> 
     <div class="commentbody"> 
      Body 
     </div> 
    </div> 
</div> 

的jQuery:

$('.ctoggle').click(function(e) { 
    $(this).parent().next('.commentholder > .commentbody').hide(); 
}) 
+1

好,你將必須有唯一的ID爲divs,如果你想訪問他們唯一。 – FlavorScape

+0

Duplicate: http://stackoverflow.com/questions/11058645/jquery-event-of-replaced-class – 2012-06-15 22:34:01

+0

@Geoist我把問題分成兩部分,因爲問題是不同的。 – DavidW

回答

2

,因爲你正在尋找的父元素兄弟的選擇相匹配的嘗試失敗:

.commentholder > .commentbody 

沒有兄弟會永遠不會匹配(.commentholder是兄弟姐妹,但你正在尋找一個孩子),所以你需要將孩子選擇器移出。您可以使用children(或find):

$('.ctoggle').click(function(e) { 
    $(this).parent().next().children('.commentbody').hide(); 
}); 
+0

非常感謝。評論人不是評論者的兄弟姐妹嗎?只是想明白。 – DavidW

+0

@DavidW - 沒問題,很高興我可以幫助:)要回答你的評論,不,'.commentbody'是'.commentholder'的*子*。兄弟姐妹是樹中同一分支的一個元素。一個孩子更深一層。 –

+0

哦,對。謝謝。我想我有一個暫時的腦凍結,由於某種原因,當我想到「兄弟姐妹」時我想到了「孩子」不知道爲什麼:) – DavidW

0
$('.ctoggle').click(function(e) { 
    $(this).parent().next().find('.commentbody').hide(); 
}) 
0

從API文檔:「獲取緊接在匹配的元素集合中的每個元素的兄弟如果提供了一個選擇,它檢索下一個兄弟只有當它匹配那個選擇器。「

所以,你的選擇器匹配兄弟姐妹的一個孩子,你會收到什麼。嘗試:

var x = $(this).parent().next('.commentholder'); 
x.find('.commentbody').hide(); 

(這部作品在你的例子)

0

給出下面的HTML:

<!DOCTYPE html> 
<html> 
<head> 
[include jQuery here] 
<meta charset=utf-8 /> 
<title>JS Bin</title> 
<!--[if IE]> 
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> 
<![endif]--> 
<style> 
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; } 
</style> 
</head> 
<body> 
    <div class="commentline"> 
    <div class="carrowholder"> 
     <div class="ctoggle">Click to toggle</div> 
     <div class="arrowwrap"> 
     </div> 
    </div> 
    <div class="commentholder"> 
     <div class="commenttitle"> 
      Title 1 
     </div> 
     <div class="commentbody"> 
      Body 1 
     </div> 
    </div> 
    <div class="commentline"> 
    <div class="carrowholder"> 
     <div class="ctoggle">Click to toggle</div> 
     <div class="arrowwrap"> 
     </div> 
    </div> 
    <div class="commentholder"> 
     <div class="commenttitle"> 
      Title 2 
     </div> 
     <div class="commentbody"> 
      Body 2 
     </div> 
    </div> 
</div> 
</body> 
</html> 

這個Javascript將工作:

$('.ctoggle').click(function(e) { 
    $(this).closest('.commentline').find('.commentbody').toggle(); 
}); 

這樣做有什麼發現DOM中的第一個元素,其類別爲.commentline(這是所有DIV的父類) nt),然後它找到所有類型爲.commentbody的DOM樹的下一個元素,這在這種情況下很好,因爲每個註釋行只有一個註釋體。如果在每個.commentline DIV中還有更多.commentbody DIV,那麼您需要進一步指定哪一個(再次使用.first().find()等)。

已經有提到的其他解決方案,但我覺得這樣的做法要稍微更具可讀性,從而維護 - 但這是我的意見:O)