所以我有一个可行的例子,但它确实缺乏健壮性和 CSS 样式。如果表始终显示其所有行,则此示例将起作用。如果您打算使用分页功能,我会问您是否可以在数据到达您的 DataTables 代码之前访问数据结构。我也没有针对数据集的动态添加或减去测试我的示例。这是 JS Fiddle 的链接。如果您有任何其他具体要求,我很乐意讨论,但希望这足以让您开始。
HTML
<table id="mydt" class="display full-width"></table>
CSS
.full-width {
width: 100%;
}
.hideMe {
display: none;
}
JS
function idCol() { return 0; /* the index of the ID column */ }
function countRowsById(rows) {
function extractId(row) { return row[idCol()]; }
function sumByGroup(prev, current) {
if(prev[current]) {
prev[current] += 1;
} else {
prev[current] = 1;
}
return prev;
}
return rows.map(extractId).reduce(sumByGroup, {});
}
$(document).ready(function() {
var dt = $('#mydt');
dt.dataTable({
pageLength: -1,
data: [
["Foo", "Bar", "Baz"],
["Fizz", "Buzz", "Bam"],
["Foo", "Boo", "Moo"],
["This", "Row", "Here"],
["That", "Row", "There"],
["This", "One", "Too"]
],
columns: [
{ title: "ID" },
{ title: "B" },
{ title: "C" },
{
title: "See More",
data: null,
orderable: false,
defaultContent: "",
class: "see-more"
}
],
order: [0, 'asc'],
drawCallback: function(settings) {
var api = this.api();
var rows = api.rows().nodes();
var rowData = api.rows().data();
var last = null;
var counts = countRowsById(rowData);
api.column(idCol()).data().each(function(idVal, index) {
// append the id to the parent row
$(rows).eq(index).data('id', idVal);
if(last !== idVal) {
if(counts[idVal] > 1) {
// There are multiple rows
// This is the first row
$(rows).eq(index).find('.see-more').html('<a href="#" class="show">Show</a>');
}
} else {
// This is a subsequent matching row
$(rows).eq(index).addClass('hideMe');
}
last = idVal;
});
}
});
function idFilter(id, i, el) {
return $(el).data('id') === id;
}
function showHideMes(id) {
dt.find('.hideMe').filter(idFilter.bind(null, id)).each(function(i, el) {
$(el).removeClass('hideMe').addClass('showMe');
});
}
function hideShowMes(id) {
dt.find('.showMe').filter(idFilter.bind(null, id)).each(function(i, el) {
$(el).removeClass('showMe').addClass('hideMe');
});
}
dt.on('click', '.see-more .show', function() {
$(this).removeClass('show').addClass('hide').html('Hide');
var rowId = $(this).parents('tr').data('id');
showHideMes(rowId);
});
dt.on('click', '.see-more .hide', function() {
$(this).removeClass('hide').addClass('show').html('Show');
var rowId = $(this).parents('tr').data('id');
hideShowMes(rowId);
});
});