0

当表格使用 dataTable 的 ajax.reload 函数自动重新加载时,我试图重新打开我的子行。(这将导致所有子行折叠)

我在互联网上找到了以下代码并尝试实现它。但这对我不起作用。https://datatables.net/forums/discussion/40777/statesave-type-option-for-child-row-state-class-of-open-row

当表重新加载时,我的浏览器控制台日志中出现以下错误。

类型错误:openTableRows 为空

希望有人可以帮助我或指出我正确的方向。

<script>
var $tagsLabel = $("<lable>");
var $tagsInput = $("<textarea>");

/* Formatting function for row details - modify as you need */
function format(d) {
    // `d` is the original data object for the row
    return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
        '<tr>' +
        '<td>Raw text:</td>' +
        '<td>' + d.Raw_html + '</td>' +
        '</tr>' +
        '</table>';
}

$(document).ready(function () {
        $table = $("#dataTable")
            .on("preInit.dt", function (e, settings) {
                $tagsLabel.append($tagsInput);
                $('.dataTables_tags').append($tagsLabel)
            })
            .on("init.dt", function (e, settings) {
                $tagsInput.tagEditor({
                    delimiter: ', ',
                    placeholder: 'Enter search keywords ...',
                    onChange: function (field, editor, tags) {
                        if (tags.length) {
                            if (tags.length > 1) {
                                $table.search(tags.join('|'), true, false).draw();
                            } else {
                                $table.search(tags[0]).draw();
                            }
                        } else {
                            $table.search('').draw(true);
                        }
                    },
                });
            }).DataTable({
                mark: true,
                "searchHighlight": true,
                "dom": '<l<"dataTables_tags"><t>ip>',
                "ajax": '/json-int',
                "columns": [
                    {
                        "class": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": '',
                        width: "5px"
                    },
                    {"data": "Timestamp", width: "135px"},
                    {"data": "Title"},
                    {"data": "Url"},
                    {"data": "domain"},
                    {"data": "Type"},
                    {"data": "Raw_html", "visible": false}
                ],
                "order": [[1, 'asc']],
                "initComplete": function () {
                    setInterval(function () {
                        $table.ajax.reload(null, false);

                        var currentdate = new Date();
                        var datetime = currentdate.getDay() + "/" + currentdate.getMonth()
                            + "/" + currentdate.getFullYear() + " @ "
                            + currentdate.getHours() + ":"
                            + (currentdate.getMinutes() < 10 ? '0' : '') + currentdate.getMinutes() + ":" + currentdate.getSeconds();
                        document.getElementById("lastUpdated").innerHTML = "Last updated: " + datetime;
                    }, 5000);
                }
            });

        var openTableRows = JSON.parse(localStorage.getItem('openRows'));

        $('#dataTable tbody').on('click', 'td.details-control', function () {
            var tr = $(this).closest('tr');
            var row = $table.row(tr);

            if (row.child.isShown()) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');

                rowIndex = row[0][0];
                var idx = openTableRows.indexOf(rowIndex);
                openTableRows.splice(idx, 1);
                localStorage.setItem('openRows', JSON.stringify(openTableRows));
                console.log(JSON.parse(localStorage.getItem('openRows')));

            } else {
                // Open this row
                row.child(format(row.data())).show();
                tr.addClass('shown');

                rowIndex = row[0][0];
                openTableRows.push(rowIndex);
                localStorage.setItem('openRows', JSON.stringify(openTableRows));
                console.log(JSON.parse(localStorage.getItem('openRows')));
            }
        });
    }
);

4

1 回答 1

2

碰巧,你查过这方面的官方手册吗?

提供的代码示例显然可以解决您的问题。对于您的特定数据表

$(document).ready(function() {
    var dt = $('#example').DataTable( {
...
})

跟踪扩展行的 ID

// Array to track the ids of the details displayed rows
    var detailRows = [];

    $('#example tbody').on( 'click', 'tr td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = dt.row( tr );
        var idx = $.inArray( tr.attr('id'), detailRows );
        if ( row.child.isShown() ) {
            ...     
            // Remove from the 'open' array
            detailRows.splice( idx, 1 );
        }
        else {
            ...
            // Add to the 'open' array
            if ( idx === -1 ) {
                detailRows.push( tr.attr('id') );
            }
        }
    } );

每次重绘数据表/调用 ajax.reload 时重新打开展开的行

// On each draw, loop over the `detailRows` array and show any child rows
    dt.on( 'draw', function () {
        $.each( detailRows, function ( i, id ) {
            $('#'+id+' td.details-control').trigger( 'click' );
        } );
    } );
于 2018-12-17T13:30:20.660 回答