2012-01-14 58 views
1

我試圖在單擊元素的父級內找到類.post-info .toggle-info。現在,頁面上的所有.post-info都會切換。我試圖得到只有一個.post-info切換它的父容器,.post。在單擊元素的父級中查找一個類

<div class="post"> 
<div class="toggle-info">Toggle Btn</div> 

<div class="post-info"> 
    <p>Toggle this content</p> 
</div> 

</div> 


$(".toggle-info").click(function() { 
    $(".post-info").animate({ 
    height: "toggle", 
    opacity:"toggle" 
    }, 520, 'swing'); 
}); 

在此先感謝您的幫助!

回答

5

你可以這樣說:

$(this).closest(".post").find(".post-info").animate(...) 

這個上升從那裏點擊發生和發現.post類的父鏈,然後發現在父.post-info,然後動畫應用到這一點。這是非常靈活的.post-info可以在.post父母的任何地方,這將工作。你可以看到它在這裏工作:http://jsfiddle.net/jfriend00/AeYZU/

對於這個特殊的確切HTML,你也可以使用這樣的:

$(this).next().animate(...) 

這會得到被點擊的股利後的下一個兄弟。請注意,這種方法(與前一種方法相反)依賴.post-info的確切位置作爲下一個兄弟,並且如果其位置改變將會中斷。你可以在這裏看到這個工作:http://jsfiddle.net/jfriend00/qGCLx/

+0

太棒了,非常感謝你的快速幫助的朋友! – pbal 2012-01-14 22:59:32

相關問題