DataTables 正在 Bootstrap 3.3.7 应用程序中使用 ajax 源数据更改列的宽度

And*_*ndy 5 html css datatables twitter-bootstrap-3

我的应用程序正在使用:

  • 数据表 1.10.16
  • 引导程序3.3.7
  • jQuery 3.2.1

设想:

我正在尝试将表单输入添加到表格的标题中,以允许按两列进行搜索。这是我的应用程序的自定义功能;它不是DataTables 提供的搜索工具。

问题:

我希望搜索输入显示为每列的全宽。我希望它看起来像这样:

在此输入图像描述

但它的渲染方式是这样的 - 请注意,搜索输入的宽度已减小:

在此输入图像描述

(由于它是私人应用程序,因此表数据很模糊)。

我使用的标记基于 Bootstrap 的列系统 - 我使用了 2 个,.col-md-6因此<th>元素宽度相等:

<table id="regulatoryInformationTable" class="table responsive display table-striped pb-25" cellspacing="0" width="100%">
    <thead>
        <th class="col-md-6">
            <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span>
                <input type="text" class="form-control" placeholder="Search Regulation Name">
            </div>
        </th>
        <th class="col-md-6">
            <div class="input-group">
                <span class="input-group-addon"><span class="glyphicon glyphicon-search"></span></span>
                <input type="text" class="form-control" placeholder="Search Regulation Data">
            </div>
        </th>
    </thead>
</table>
Run Code Online (Sandbox Code Playgroud)

如果我使用此标记打开页面,它将按照第一个屏幕截图进行渲染 - 但表中没有任何数据 - 因为我此时尚未发出 ajax 请求并更新 DataTable。

当我发出 ajax 请求时,表已填充,但输入的宽度似乎缩小了。我使用DataTables并发出ajax请求的js如下:

$(function() {

    /* Populate table of Regulatory Information */
    var regulatoryInformationTable = $('#regulatoryInformationTable').DataTable({
        "processing": true,
        "serverSide": true,
        "searching": false,
        "ajax": {
            "url": "/get-data.json",
            "method": "POST",
            "cache": false,
            "dataSrc": function (json) {
                return json.data;
            }
        },
        "columns": [
            {"data": "display_label", "name": "display_label"},
            {"data": "display_value", "name": "display_value"},
        ],
        "columnDefs": [
            {"width": "50%", "targets": 0},
            {"width": "50%", "targets": 1},
            {"orderable": false, "targets": [0,1]} // Can't order
        ],
        "paging": false, // no pagination
        "language": {
            "zeroRecords": "Sorry we no data for this substance",
            "infoFiltered": "",
            "infoEmpty": "",
            "processing": '<i class="fa fa-spinner fa-spin fa-2x fa-fw"></i>'
        }
    });   
}); 
Run Code Online (Sandbox Code Playgroud)

我已经使用columnDefs数组来指定width: 50%,但这没有任何区别 - 即使我删除它。

谁能建议如何解决这个问题?

小智 1

似乎 DataTables 将 的 设置widthth固定值。这应该会切断内部的输入。尝试禁用该autoWidth选项。保留您定义的其他选项。

$('#regulatoryInformationTable').dataTable( {
  "autoWidth": false,
} );
Run Code Online (Sandbox Code Playgroud)

参考: //datatables.net/reference/option/autoWidth

不要col-*在表格上使用 Bootstrap 类,让表格自由流动,这些类用于布局。