2011-10-20 28 views
5

我有這樣的功能:JQuery的查找下一個元素內錶行

$("span.expandimg").click(function(){ 
    $(this).nextAll(".toggle_container:first").slideToggle("slow"); 
}); 

,隨着工作的罰款:

<span class="expandimg"><a href="#"><img id="iexpand" src="images/expand.png" border="0" /><img id="icollapse" src="images/collapse.png" border="0" /></a></span>&nbsp;<a href="asdfa" class="DSF">First Link</a> 

<div class="toggle_container"> 
Some Text 
</div> 

但現在我把「expandimg」表列和「toggle_container內「在另一欄內。類似這樣的:

<tr> 
    <td><span class="expandimg">......</td> 
    <td><div class="toggle_container">.....</td> 
<tr> 

我現在怎麼找到「toggle_container」元素?我想單擊「expandimg」展開「toggle_container」,但它不適用於我擁有的功能。

謝謝!

+0

http://api.jquery.com/category/traversing/ – Blazemonger

+0

是的,我認爲你應該使用.parent():$(本).parent()。父母()。查找('。toggle_container')... http://api.jquery.com/parent/ – biziclop

+1

@RaduBilei:你爲什麼不張貼作爲答案的任何理由? –

回答

10
$("span.expandimg").click(function(){ 
    $(this) 
     .closest("tr") 
     .find("td .toggle_container") 
     .slideToggle("slow"); 
}); 
0

隨着HTML你現在有這應該工作 -

$("span.expandimg").click(function(){ 
    $(this).parent().siblings().find(".toggle_container:first").slideToggle("slow"); 
}); 

演示 - http://jsfiddle.net/QAkKP/

+0

不需要做「兄弟姐妹」,然後「找到」,直接去找「尋找」。 – Shef

+0

實際上你做得對,你是以另一種方式做的,這可能會慢一些,這取決於OP將在那裏存在的表格單元的數量。另外,不需要用'tr'的所有'td'元素構造一個對象。 – Shef

0
$("span.expandimg").click(function(){ 
    $(this).parents("tr").find(".toggle_container").slideToggle("slow"); 
}); 

上升到父TR元素,搜索,對於.toggle_container。

應該工作:)

+1

這將比「最接近」的方式慢,而且它將構建整個父樹的一個對象,而不僅僅是直接的對象。 – Shef

相關問題