JQuery DataTables: How to show/hide row details wi

2019-07-28 19:25发布

问题:

I am basically trying to combine code from two examples given in the DataTables documentation. The first example shows how to have multiple DataTables on one page, while the other allows you to show/hide details about each row.

I have applied the class "dataTable" to each of my dynamically generated tables, so the following code turns them all into DataTables (and disables sorting on the first column since that's where the show/hide icon goes):

var oTable = $('.dataTable').dataTable({
    "aoColumnDefs" : [ {
        "bSortable" : false,
        "aTargets" : [ 0 ]
    } ],
    "aaSorting" : [ [ 1, 'asc' ] ]
})

Then I add an event listener to show/hide the additional row of details when the user clicks the image in the first column:

$('.dataTable tbody td img').live('click', function() {
    var nTr = $(this).parents('tr')[0];

    if (oTable.fnIsOpen(nTr)) {
        /* This row is already open - close it */
        this.src = "../examples_support/details_open.png";
        oTable.fnClose(nTr);
    } else {
        /* Open this row */
        this.src = "../examples_support/details_close.png";
        oTable.fnOpen(nTr, fnFormatDetails(), 'details');
    }
});

The problem is that this only works for the first DataTable on the page. When I click the show/hide icon in a row on any other table, the icon changes, but the details row does not appear. Further clicks on the same icon have no effect. Does anyone have any idea how to show/hide detail rows when using multiple DataTables on one page? I appreciate your help.

回答1:

since you are defining

var oTable = $('.dataTable').dataTable( \\YOURSTUFF)`;

your variable oTable has all your dataTables as its value.

The only thing you have to do is, to get the dataTable that contains your clicked element. You can achieve this by adding

tbl = $(this).parent().parent().dataTable();

to your click function and change all oTable calls to tbl.

Have fun playing around with it ;-)