我有以下标记:
<table class="tableM">
<tr class="accordion">
<th>Hello</th>
</tr>
<tr>
<td class="tableMCell">
Hi!
</td>
</tr>
<tr class="accordion">
<th>Goodbye</th>
</tr>
<tr>
<td class="tableMCell">
Cya!
</td>
</tr>
</table>
当用户点击其中一个标题时,我会应用 Accordion 效果:
$(function () {
$(".tableM tr:not(.accordion)").hide();
$(".tableM tr:first-child").show();
$(".tableM tr.accordion").click(function () {
$(this).nextAll("tr").fadeToggle(200);
});
});
这在一定程度上工作正常,但是当单击顶部标题时,即 <th>Hello</th>
期望的效果是它只显示下一个 tr
包含 Hi!
信息。然而,它也揭示了 <th>Goodbye</th>
下的内容。也排?我该如何解决这个问题,以便单击任一行时它只显示它们各自的内容而不是所有内容?
只需使用 .next()
而不是 .nextAll()
$(this).next("tr").fadeToggle(200);
原因是.nextAll()
将选择下一个 <tr>
的全部而不是仅仅选择下一个。
$(function() {
$(".tableM tr:not(.accordion)").hide();
$(".tableM tr:first-child").show();
$(".tableM tr.accordion").click(function() {
$(this).next("tr").fadeToggle(200);
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="tableM">
<tr class="accordion">
<th>Hello</th>
</tr>
<tr>
<td class="tableMCell">
Hi!
</td>
</tr>
<tr class="accordion">
<th>Goodbye</th>
</tr>
<tr>
<td class="tableMCell">
Cya!
</td>
</tr>
</table>
要将其他 Accordion 切换回来,您需要获取它们并将它们淡出
$(this).next("tr").fadeToggle(200) // this is what you have now
.end().siblings('.accordion').next("tr").fadeOut(200);
// ^ this will select the other accordions and toggle their content.
它是如何工作的。
$(this).next("tr").fadeToggle(200) // toggles the next accordion content, the selector is now .next('tr') meaning the content
.end() // this returns the selector one step back to $(this) / the tr you clicked on
.siblings('.accordion') // gets all tr with the class accordion that are in the same table
.next("tr").fadeOut(200) // toggles the content of the siblings
我是一名优秀的程序员,十分优秀!