我是jQuery的新手,正在逐步学习。我实现了表的第一部分,默认情况下扩展了行。如何添加切换以默认折叠?我在tr上尝试了.hide(),但语法似乎错误。
这是我的代码:
$(function() {
$('#mytable').on('click', '.toggle', function() {
//Gets all <tr>'s of greater depth
//below element in the table
var findChildren = function(tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function() {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var tr = el.closest('tr'); //Get <tr> parent of toggle button
var children = findChildren(tr);
var subnodes = children.filter('.expand');
subnodes.each(function() {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (tr.hasClass('collapse')) {
tr.removeClass('collapse').addClass('expand');
children.hide();
} else {
tr.removeClass('expand').addClass('collapse');
children.show();
}
return children;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> </p>
<table class="blueTable" id="mytable">
<thead>
<tr>
<th> Release </th>
<th> Attribute Value </th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="11"> </td>
</tr>
</tfoot>
<tbody>
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span><b>R2019</b></td>
<td> </td>
</tr>
<tr data-depth="1" class="collapse level1">
<td>Cluster</td>
<td>R2019.2</td>
</tr>
</tbody>
</table>
我尝试在tr值上使用hide(),但看起来好像丢失了一些东西。