提问人:ttoshiro 提问时间:8/3/2020 更新时间:8/3/2020 访问量:160
如何使用jQuery / JavaScript使可扩展的表格单元格默认隐藏,并且可以在标签外部单击?
How to make expandable table cells hidden by default using jQuery/JavaScript, and click-able outside of a label?
问:
我有一段简短的代码,允许折叠表格的各个部分(它们就像可折叠的标题)。这很整洁,但我试图在加载页面时发生相反的情况——默认情况下在加载时折叠,但在单击时可以展开。我该怎么做?
我目前的代码(如下所示)还具有仅在单击该部分中的单词时折叠的部分,而不是在单击该部分本身(单词之外)时折叠的部分。这是因为我使用标签使可折叠。有没有办法使整行可展开/可折叠?
table {
width: 100%;
}
table,
tr,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-family: Arial;
}
[data-toggle="toggle"] {
display: none;
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tbody class="labels">
<tr>
<td colspan="2">
<label for="section">Click me!</label>
<input type="checkbox" id="section" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Jack</td>
<td>100</td>
</tr>
<tr>
<td>Jill</td>
<td>300</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('[data-toggle="toggle"]').change(function() {
$(this).parents().next('.hide').toggle();
});
});
</script>
答:
1赞
Marc
8/3/2020
#1
这里发生了几件事......
- 你隐藏了你的复选框,我认为这不是你的本意。
- 看看这个例子,我修复了一些问题:https://jsfiddle.net/za73qf65/
修复包括:
- 将“hide”类的名称更改为“hidable”
- 将“hidable”类默认为
display:none
- 取消隐藏复选框
- 将事件处理程序更改为 (可选)
change()
click()
- 将事件处理程序附加到具有 ID 的按钮(可以对其进行更改)
关键是,通过我的更改,您的示例有效。您可能希望根据更具体的需求对其进行调整。
2赞
dale landry
8/3/2020
#2
我试图在加载页面时发生相反的情况—— 默认情况下在加载时折叠,但在单击时可展开。如何 我会继续这样做吗?
只需在 jquery 中在切换函数上方添加一行,然后调用 .hide 类选择器并使用 .hide();
然后,当您单击它时,切换功能将触发。
还具有仅在 部分被点击,而不是当部分本身(在 words) 被点击。这是因为我使用标签来制作 湿 陷 性。有没有办法使整行 可扩展/可折叠?
是的。。。使标签在CSS文件中显示为块...
label {
display: block;
}
$(document).ready(function() {
$('.hide').hide();
$('[data-toggle="toggle"]').change(function() {
$(this).parents().next('.hide').toggle();
});
});
table {
width: 100%;
}
table,
tr,
th,
td {
border: 1px solid black;
border-collapse: collapse;
font-family: Arial;
}
[data-toggle="toggle"] {
display: none;
}
label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
</thead>
<tbody>
<tbody class="labels">
<tr>
<td colspan="2">
<label for="section">Click me!</label>
<input type="checkbox" id="section" data-toggle="toggle">
</td>
</tr>
</tbody>
<tbody class="hide">
<tr>
<td>Jack</td>
<td>100</td>
</tr>
<tr>
<td>Jill</td>
<td>300</td>
</tr>
</tbody>
</table>
评论
0赞
ttoshiro
8/3/2020
了不起!非常感谢。
评论