2010-03-11 90 views
2

我有結構像這樣的表:切換錶行的兄弟姐妹

<table> 
<tr id="id1" class="parent"></tr> 
<tr class="id1"></tr> 
<tr class="id1"></tr> 
<tr class="id1"></tr> 
<tr class="id1"></tr> 

<tr id="id2" class="parent"></tr> 
<tr class="id2"></tr> 
<tr class="id2"></tr> 
<tr class="id2"></tr> 
<tr class="id2"></tr> 

.....etc 
</table> 

正如你可以看到子類coresponding他們的父ID。現在,我想要切換父類行被點擊時所有具有與父行ID相同的行的行。

我曾經嘗試這樣做,也許是愚蠢的嘗試:)似乎並不能得到這個工作:

$('tr.parent').click(function() { 
    //alert('yay'); 
    var tog = $(this).attr('id'); 
    $(this).siblings().hasClass(tog).slideToggle(); 
    return false; 
    }); 

感謝。

回答

3

快到了,這裏亞喲:

$('tr.parent').click(function() { 
    var tog = $(this).attr('id'); 
    $(this).siblings('.' + tog).slideToggle(); 
    return false; 
}); 

.hasClass()返回一個布爾值,它會檢查,如果一個元素有一個類,你要通過類來過濾。 .siblings()接受選擇器過濾器,see here for details

如果子行總喜歡你的例子後的,你可以使這個多一點效率的前鋒只有.nextAll()這樣查找:

$('tr.parent').click(function() { 
    $(this).nextAll('.' + $(this).attr('id')).slideToggle(); 
}); 
+0

啊,是的,當然。奇蹟般有效。尼克,非常感謝你。 – swan 2010-03-11 21:21:22

+0

@kuswantin - 歡迎:) – 2010-03-11 21:23:01

0

jQuery代碼:

<script type="text/javascript"> 
    $(document).ready(function() { 

     $('table').children('tbody').toggle(false); 
     $(".lnkToggle").bind('click', function() { 
      $(this).closest('table').children('tbody').toggle(); 
     }); 

    }); 
</script> 

HTML表格:

<table class="table table-striped"> 
    <thead> 
     <tr> 
      <th style="text-align: left; width: 250px;"> 
       <i class="lnkToggle" title="Click to view cases"> + </i> 
       MOVIES 
      </th> 
     </tr> 
    </thead> 

    <tbody> 
     <tr> 
      <td>MATRIX</td> 
     </tr> 
     <tr> 
      <td>TOY STORY</td> 
     </tr> 
     <tr> 
      <td>THE GOONIES</td> 
     </tr> 
    </tbody> 
</table>