折叠扩展的html表

时间:2019-03-15 12:46:28

标签: javascript jquery html html5

我以HTML表和jQuery脚本为例,我试图更改此组合的行为。当前,表行在click上展开和折叠。如何将其更改为折叠并在click上展开。

$('.header').click(function() {
  $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});
table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
}

.header .sign:after {
  content: "+";
  display: inline-block;
}

.header.expand .sign:after {
  content: "-";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="0">
  <tr class="header expand">
    <th colspan="2">Header <span class="sign"></span></th>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header expand">
    <th colspan="2">Header <span class="sign"></span></th>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>

Fiddle

2 个答案:

答案 0 :(得分:2)

要反转默认状态,您只需要从expand元素中删除.header类,并在标准display: none元素上设置tr。否则JS逻辑是相同的。

tr.header {
  cursor: pointer;
  display: table-row;
}

tr {
  display: none;
}

Updated fiddle

答案 1 :(得分:1)

为了使折叠具有展开行为,请首先隐藏行:

 $('.header').nextUntil('tr.header').hide(); 

$('.header').nextUntil('tr.header').hide();
$('.header').click(function() {
  $(this).toggleClass('expand').nextUntil('tr.header').slideToggle(100);
});
table,
tr,
td,
th {
  border: 1px solid black;
  border-collapse: collapse;
}

tr.header {
  cursor: pointer;
}

.header .sign:after {
  content: "+";
  display: inline-block;
}

.header.expand .sign:after {
  content: "-";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table border="0">
  <tr class="header expand">
    <th colspan="2">Header <span class="sign"></span></th>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr class="header expand">
    <th colspan="2">Header <span class="sign"></span></th>
  </tr>
  <tr>
    <td>date</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <td>data</td>
    <td>data</td>
  </tr>
</table>