html嵌套表通过单击表行第一个td来隐藏或显示表行

html nested table hide or show table row by clicking table row first td

本文关键字:隐藏 显示 td 第一个 单击 html 嵌套      更新时间:2023-09-26

我正在做一个项目,我想在其中以嵌套表结构显示数据,就像在链接中一样

http://www.aspdotnet-suresh.com/2012/05/gridview-with-in-gridview-or-nested.html

请查看下面的演示。它是在asp.net的网格视图中实现的。但我正在尝试在html中实现。我得到了解决方案,但问题是,在那个表中,如果我点击行中的任何位置,它就会显示下一行。但我需要先点击tr的td,然后只需要显示tr,其他什么都不显示,
下面是我的html代码。请任何人帮帮我。

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
$(function() {
  $(".toptable > tbody > tr:not(.accordion)").hide();
  $(".toptable tr:first-child").show();
  $(".toptable tr.accordion").click(function(){
  $(this).next().fadeToggle();
    });
  });
</script>
</head>
<body>
<table class="toptable" border="1">
                <tbody>                   
                    <tr class="accordion">
                        <td class="id1">TD1</td>
                        <td>TD2</td>
                        <td>TD3</td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <table class="nested" border="1" >
                                <tbody>
                                    <tr>
                                        <td>nestedTD1</td>
                                        <td>nestedTD2</td>
                                    </tr>
                                    <tr>
                                        <td>nestedTD3</td>
                                        <td>nestedTD4</td>
                                    </tr>
                                </tbody>
                            </table>          
                        </td>
                     </tr>
                     <tr class="accordion">
                        <td>TD1</td>
                        <td>TD2</td>
                        <td>TD3</td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <table class="nested" border="1" >
                                <tbody>
                                    <tr>
                                        <td>nestedTD1</td>
                                    </tr>
                                    <tr>
                                        <td>nestedTD3</td>

                    </tr>
                </tbody>
            </table>
</body>
</html>

使用选择器中的td:first选择第一个td,parent().next()切换下一个tr

试试这个

 $(".toptable tr.accordion td:first").click(function(){
                       //--^^^^^^^^---here
     $(this).parent().next().fadeToggle();
      //----^^^^^^^^^---here
});

更新

在下面的评论之后

它不适用于第二行。这意味着如果我首先点击第二行td,它必须显示其他表行。

试试这个

$(".toptable tr").find('td:first').click(function(){
     $(this).parent().next().fadeToggle();
});

工作小提琴