2009-08-28 45 views
7

這裏是我的HTML:使用Jquery closest()函數?

<tr> 
    <td class="show_r3c">click here</td> 
</tr> 
<tr class="r3c"> 
    <td>This is what I'd like to display</td> 
</tr> 

而且目前我有這個jQuery代碼,

$(document).ready(function(){ 
     $(".r3c").hide();   
     $('.show_r3c').click(function() { 
         $(this).closest('.r3c').toggle(); 
         return false; 
     }); 
    }); 

出於某種原因,closest()功能無法正常工作,也不會切換錶行.r3c - 我試過使用父母和其他替代品,但不能得到它的工作:(

道歉的愚蠢的問題,以及類似的問題,我以前有過。只是想知道什麼是最好的解決方案?

謝謝!

回答

12

與嘗試:

$('.show_r3c').click(function() { 
    $(this).parent('tr').next('tr.r3c').toggle(); 
    return false; 
}); 
4

也許這會工作:

$(document).ready(function(){ 
    $(".r3c").hide(); 

    $('.show_r3c').click(function() { 
     $(this).parent().siblings(":first").toggle(); 
     return false; 
    }); 
}); 
+0

,是完美,謝謝! :) – Nick 2009-08-28 13:35:31

21
最接近

()查找最近的父不是父母,兄弟姐妹的孩子。

你想要的東西,如:

$(document).ready(function(){ 
    $(".r3c").hide(); 

    $('.show_r3c').click(function() { 
     $(this).closest('table').find("tr.r3c").toggle(); return false; 
    }); 
}); 
+1

由於問題是'使用Jquery最接近()函數?'這肯定是最好的答案。其他答案是mroe關於如何使用jquery遍歷DOM而不使用最接近的:) – 2009-09-22 01:05:29

+1

+1幫助我out..thx! – 2010-05-06 16:14:02