我有一个看起来像这样的表:
<table>
<thead>
<tr><th>Customer</th><th>Order</th><th>Month</th></tr>
</thead>
<tbody>
<tr><td>Customer 1</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 1</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 1</td><td>#3</td><td>March</td></tr>
</tbody>
<tbody>
<tr><td>Customer 2</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 2</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 2</td><td>#3</td><td>March</td></tr>
</tbody>
<tbody>
<tr><td>Customer 3</td><td>#1</td><td>January</td></tr>
<tr><td>Customer 3</td><td>#2</td><td>April</td></tr>
<tr><td>Customer 3</td><td>#3</td><td>March</td></tr>
</tbody>
....
.... 10s of records like this
</table>
我想让每个tbody元素可点击(可折叠),以便在折叠状态下,我会得到内部的内容(比如Customer 1 | 3 Entries
)的摘要,并且在扩展状态下,我会看到实际的行。
这可以针对如上所示的结构表进行吗?
JSFiddle:http://jsfiddle.net/Ju4xH/
答案 0 :(得分:5)
它有点乱,动画不起作用(我猜它是因为它在<tr>
上,但这就是我想出的:
$(document).ready(function () {
$("table").on("click", "tbody", function () {
var $this = $(this);
var myTRs = $this.children("tr");
if ($this.hasClass("collapsed")) {
$this.removeClass("collapsed");
myTRs.first().remove();
myTRs.show();
} else {
$this.addClass("collapsed");
var newInfo = myTRs.first().children("td").first().text() + " | " + myTRs.length + " entries";
myTRs.hide();
$this.prepend($("<tr><td colspan='3'>" + newInfo + "</td></tr>").hide()).find("tr").first().slideDown();
}
});
});
DEMO: http://jsfiddle.net/ZhqAf/1/
当您点击未折叠的<tbody>
时,它会隐藏行并添加一个包含您想要的详细信息的新行。单击折叠的<tbody>
时,它会删除新的“详细信息”行,并显示原始行。
答案 1 :(得分:2)
我通过计算tbody
中的行数来包含每行的标题,并在插入后绑定每个标题上的click事件以显示tbody
的内容。
$(document).ready(function(){
$('table tbody').each(function(){
var num=$(this).children().length;
// alert(num);
$(this).before("<div id='header' class='header'>"+num +" entries </div>");
//alert($(this).html());
$(this).hide();
});
$('.header').on('click',function(){
$(this).next().slideToggle("slow");
});
});
<强> EDITED 强>
如果你真的想要幻灯片动画,你可以将所有tbody
也包装在一个div中。所以slideToggel
也会给你动画。您可以按如下方式使用它:
$(document).ready(function(){
$('table tbody').each(function(){
var num=$(this).children().length;
// alert(num);
$(this).before("<div id='header' class='header'>"+num +" entries </div>");
//alert($(this).html());
$(this).wrap('<div class="new" />');
$('.new').hide();
});
$('.header').on('click',function(){
$(this).next().slideToggle("slow");
$(this)
});
});