Jquery 显示/隐藏使用单击事件随机生成的表元素

Jquery 显示/隐藏使用单击事件随机生成的表元素,jquery,html,Jquery,Html,我有多个随机生成的表。我只希望显示每个表的第一行,而隐藏其余行。当我单击表的可见行时,我希望它的其余行/内容显示/隐藏。我将如何使用Jquery实现这一点 您应该编写如下函数: function AttachEvent(tableId) { $("#" + tableId + " tbody tr:first-child").click(ToggleRows); } function ToggleRows(e) { // get src table of e // yo

我有多个随机生成的表。我只希望显示每个表的第一行,而隐藏其余行。当我单击表的可见行时,我希望它的其余行/内容显示/隐藏。我将如何使用Jquery实现这一点

您应该编写如下函数:

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,它会将事件绑定到第一行

这些函数假定生成该表时,除第[0]行外的所有行都设置为“显示:无”


我还没有测试过这个,但是这个理论应该是可行的。您可能需要更改一些内容,例如绑定哪个事件,以及是使用tr还是tds来显示/隐藏。

要隐藏除第一行以外的所有行,请执行以下操作:

$("table tbody tr:not(:first-child)").hide();
要在单击第一行时使其可见,请执行以下操作:

$("table tbody tr:first-child").click(function() {
  $(this).siblings().show();
});
或者,您可能希望以稍微不同的方式组织您的桌子(如果可能):


表tbody tr{display:none;}
$(函数(){
$(“表thead tr”)。单击(函数(){
$(“tbody tr”,$(this).parents(“table”)[0]).show();
});
});
... 第一排在车斗里,而不是车斗里。。。
... 第1行。。
... 第2行。。
... 第3行。。

有很多方法可以剥下这只猫的皮。

我遇到了类似的需求,但是show/hide tbody(jQuery在尝试切换很多行时似乎崩溃了)。我的表由类“datatable”标识,我使用基于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规范使用AD和tbody组织的。 另见

$(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(); });

})