2009-04-08 38 views

回答

2

要隱藏所有行,但第一:

$("table tbody tr:not(:first-child)").hide(); 

爲了讓他們看到當你點擊第一行:

$("table tbody tr:first-child").click(function() { 
    $(this).siblings().show(); 
}); 

或者你可能要組織你的表稍有不同(如果可能的話):

<style type="text/css"> 
table tbody tr { display: none; } 
</style> 
<script type="text/javascript"> 
$(function() { 
    $("table thead tr").click(function() { 
    $("tbody tr", $(this).parents("table")[0]).show(); 
    }); 
}); 
</script> 
<table> 
<thead> 
    <tr> ... first row is in thead not tbody ... </tr> 
</thead> 
<tbody> 
    <tr> ... row1 .. </tr> 
    <tr> ... row2 .. </tr> 
    <tr> ... row3 .. </tr> 
</tbody> 
</table> 

有很多方法來剝皮這隻特定的貓。

1

你應該寫一些功能是這樣的:

function AttachEvent(tableId) 
{ 
    $("#" + tableId + " tbody tr:first-child").click(ToggleRows); 
} 

function ToggleRows(e) 
{ 
    // get src table of e 
    // you can find code for this on SO or quirksmode.org (or basically anywhere) 

    $(src).find("tr").hide(); 
    $(src).find("tr:first-child").show(); 
} 

如果調用的attachEvent與表的id產生時,它會綁定事件的第一行。

這些函數假定該表的所有行都被設置爲display:none。

我沒有測試過這個,但理論應該工作。你可能需要改變一些事情,比如綁定哪個事件,以及是否使用tr或tds來顯示/隱藏。

0

我遇到了類似的需求,但顯示/隱藏tbody(jQuery在嘗試切換大量行時似乎崩潰了)。我的表是由類「數據表」確定我用.toggle()(可自jQuery的1.0版本)的基礎上克萊圖斯的解決方案:

$(document).ready(function() { 
     //SK toggles datatables (show/hide tbody when clicking thead) 
     $('table.datatable thead tr').on('click', function(event) { 
      $('tbody', $(this).parents('table')[0]).toggle(); }); 

}) 

這裏假設你有你的表根據與THEAD和HTML5規範組織TBODY。 另請參閱http://api.jquery.com/toggle/