javascript - DataTables:在 ajax.reload 上重新打开折叠的子行

标签 javascript jquery datatables

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

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

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

TypeError: openTableRows is null

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

<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')));
            }
        });
    }
);

最佳答案

偶然,你查过 official manual在这方面?

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

$(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' );
        } );
    } );

关于javascript - DataTables:在 ajax.reload 上重新打开折叠的子行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53813846/

相关文章:

javascript - 数据表 - 下一个/上一个分页链接显示下一个/上一个完整的页码组

javascript - IndexedDB 支持类似 SQL 的事务吗?

javascript - jQuery 在 insertBefore 之后触发点击

javascript - 在 API Client 中公开 Expressjs 中间件

javascript - 自动完成两个字段没有任何反应

javascript - 将单页网站上的 <section> 变暗

c# - 在c#中将数据保存在嵌套的for循环中

javascript - 未捕获的类型错误 : Cannot read property 'row' of undefined is not working in angular js

javascript - 垂直/水平堆叠 6 到 8 个 div 的旋转木马(房间布局)控制 slider

javascript - 答案按钮(正确、错误、是和否)未出现