【发布时间】:2009-04-08 13:34:31
【问题描述】:
我有多个随机生成的表。我只希望显示每个表的第一行,其余行隐藏。当我单击表格的可见行时,我希望其其余行/内容显示/隐藏。我将如何使用 Jquery 完成此任务?
【问题讨论】:
我有多个随机生成的表。我只希望显示每个表的第一行,其余行隐藏。当我单击表格的可见行时,我希望其其余行/内容显示/隐藏。我将如何使用 Jquery 完成此任务?
【问题讨论】:
隐藏除第一行以外的所有行:
$("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>
有很多方法可以给这只猫剥皮。
【讨论】:
你应该写一些这样的函数:
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();
}
如果在生成表时使用表的id调用AttachEvent,它会将事件绑定到第一行。
这些函数假定生成的表格中除了 row[0] 之外的所有行都设置为 display:none。
我尚未对此进行测试,但该理论应该可行。您可能需要更改一些内容,例如要绑定哪个事件,以及是使用 tr 还是 tds 来显示/隐藏。
【讨论】:
我遇到了类似的需求,但显示/隐藏 tbody(尝试切换大量行时 jQuery 似乎崩溃了)。我的表由类“数据表”标识,我使用基于 Cletus 解决方案的 .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(); });
})
这假设您根据 html5 规范使用 thead 和 tbody 组织表格。 另见http://api.jquery.com/toggle/
【讨论】: