简体   繁体   中英

JQuery DataTable: Set colspan of column title dynamically

Unlike in the example provided by documentation, I want to make column title span dynamically.

I have generated sample data

var data = [];

for (var i = 0; i < 4; ++i) {
    for (var j = 0; j < 4; ++j) {
        var dataRow = [];
        dataRow.push ("10" + (i + 1));
        dataRow.push ("A");
        for (var k = 0; k < 8; ++k) {
            dataRow.push ("B");
            dataRow.push ("test");
        }
        data.push (dataRow);
    }
}

tried to generate header via columnDefs

var columnDefs = [
    {
        title: "title",
        targets: [0, 1]
    }
];

for (i = 0; i < 8; ++i) {
    columnDefs.push ({
        title: "data" + i,
        targets: [(i + 1) * 2, (i + 1) * 2 + 1]
    });
}

and generated table

$("#table").DataTable({
    columnDefs: columnDefs,
    data: data,
    rowsGroup: [
        0
    ],
    responsive: true,
    paging: false,
    searching: false,
    fixedHeader: true,
    fixedColumns: {
        leftColumns: 2
    },
    scrollX: true,
    scrollY: "200px",
    scrolLCollapse: true,
    info: false,
    ordering: false
});

but table duplicated title on each column assigned by targets field. Is there any way I can merge them (effectively making th s have colspan of 2)?

Demo

To make the DataTable colspan work requires a second header row, one that has a single header cell for each column.

Quote from https://datatables.net/examples/advanced_init/complex_header.html :

Note that each column must have at least one unique cell (ie a cell without colspan) so DataTables can use that cell to detect the column and use it to apply ordering.

But to answer your question on how to add headers with colspan dynamically, you can do the following:

var headers = '<thead><tr><th colspan="2">Title</th><th colspan="2">1</th><th colspan="2">2</th><th colspan="2">3</th><th colspan="2">4</th><th colspan="2">5</th><th colspan="2">6</th><th colspan="2">7</th><th colspan="2">8</th></tr>';
headers += '<tr><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th><th></th></tr></thead>';

$("#table").append(headers);

$("#table").DataTable({...});

Updated demo: https://jsfiddle.net/pn4aLmpb/1/

To give it the correct appearance you may be able to apply a height of 0 to this second row. Note that display:none won't work as the headers will no longer align with the row data. This is because behind the scenes DataTable cleverly generates several overlapping HTML tables to simulate the effects of frozen rows, columns and headings, so there is a distinct disconnect between the column data and the column headings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM