html - “刷新”行数据后的数据表列宽问题
问题描述
我目前正在使用数据表来生成下表:
我对结果很满意,因为每列的宽度是自动计算的,每行产生 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 函数时出现问题,表格列将以某种方式调整大小并如下所示:
每列的宽度调整大小,每行 3 行,随后单击过滤器按钮将保持此格式。有人知道如何避免这种列宽重新计算吗?
解决方案
显然,这是因为数据表将宽度属性分配给所有 th。
添加 autoWidth false 属性可以防止这种情况。
$('#tableBody').parent().DataTable({"autoWidth": false});
然后由网络浏览器(例如chrome)自动计算宽度
推荐阅读
- video - 获取 VMAF 指标以及 PSNR 等其他指标
- reactjs - Meteor Admin 用户未访问所有用户集合
- c++ - C++ Xcode 库 - 未声明的 math.h 功能
- ios - 如何区分何时使用通知启动应用程序与仅通过通知将应用程序带到前台
- swift - 计算有多少自定义注释被添加到 mapView swift 4
- list - Tcl/sh:从嵌套列表中返回元素?
- python - Tensorflow AttributeError:“numpy.float32”对象没有属性“值”
- java - 如何将 apache commons cli 与 log4j 一起使用?
- bash - Bash 使用 sed 命令在 LaTeX .cls 文件中用 % 注释一行
- mysql - MySql SumIF 来自另一个表而不更改值的顺序