“刷新”行数据后出现数据表列宽问题

时间:2019-04-21 04:25:53

标签: html datatables bootstrap-4 material-design

我目前正在使用数据表生成以下表格:

enter image description here

我对结果感到满意,因为每列的宽度是自动计算的,每行产生1行,看起来很棒。上表是通过API使用以下简单代码生成的:

var dataTable;

// This is the button with text "Filter" as shown in screenshot
$('#search').click(function(e) {
    e.preventDefault();

    if (dataTable) {
        dataTable.clear();
        dataTable.destroy();
    }

    $.ajax({ 
        type : "GET", 
        url : contextPath + "/api/company/list", 
        contentType : "application/json;charset=utf-8", 
        data : { token : token(), name: $('#name').val() }, 
        success : function(data) {
            if (data) {
                var tag = '';

                for (var i = 0; i < data.length; i++) {
                    var c = data[i];

                    tag += '<tr>' 
                        + '<td>' + (i + 1) + '</td>' 
                        + '<td>' + c.name + '</td>' 
                        + '<td>' + c.registrationNumber + '</td>' 
                        + '<td>' + c.createdTime + '</td>'
                        + '<td>'
                        + ' <a href="' + contextPath + '/company?id=' + c.id + '" target="_blank"><i class="fa fa-fw fa-search text-info"></i></a>'
                        + ' <a href="' + contextPath + '/company/update?id=' + c.id + '"><i class="fa fa-fw fa-edit text-warning"></i></a>' 
                        + '</td>'
                        + '</tr>';
                }

                $('#tableBody').html(tag);
                dataTable = $('#tableBody').parent().DataTable();
            } else {
                alert("Oops, there's an error! Please reload the page");
            }
        }, error : function(xhr) {
            alert("Oops, there's an error! Please reload the page");
            console.log(xhr);
        }
    });
});

表html的代码段

<div class="card-body">
    <div class="table-responsive">
        <table class="table data-table">
            <thead class=" text-primary">
                <th>#</th>
                <th>Name</th>
                <th>Registration Number</th>
                <th>Date Created</th>
                <th></th>
            </thead>
            <tbody id="tableBody">

            </tbody>
        </table>
    </div>
</div>

但是,当我单击过滤器按钮并重新运行相同的onClick函数时,会出现问题,表格列将以某种方式调整大小并显示在下面:

enter image description here

调整每列的宽度,使每行3行,随后单击“过滤器”按钮将保持此格式。有人知道如何避免这种列宽重新计算的事情吗?

1 个答案:

答案 0 :(得分:0)

显然是因为数据表将width属性分配给所有th。

添加autoWidth false属性可以防止这种情况。

$('#tableBody').parent().DataTable({"autoWidth": false});

然后通过网络浏览器(例如chrome)自动进行宽度计算

相关问题