jquery - 数据表: fixed width for selected columns only

标签 jquery datatable datatables

我有一个表,其列数不固定。但是,前 3 列始终存在。

因此,以下属性在我的情况下不起作用(因为需要在该方法中固定列数)

"aoColumns": [
        {"sWidth": "50px"},
        {"sWidth": "100px"},
        {"sWidth": "100px"},
        null,
        null,
        null
    ]
 } );

我尝试过类似的方法:

"aoColumns": [[1, { "sWidth": "50px" }] ]

这也不起作用,因为它会产生一些错误。

请大家推荐一个好的方法

最佳答案

为什么不让函数动态生成 aoColumns 数组?

// function that generates the aoColumns-array based on the tables <thead>
// columns beyond #3 get a fixed 25px width (just to be illustrative)
// expand the switch if certain columns need certain fixed widths
function aoColumns() {
    var ao = [];
    $("#table th").each(function(i) {
        switch (i) {
            case 0 : 
                ao.push({"sWidth": "50px"});
                break;
            case 1 : 
                ao.push({"sWidth": "100px"});
                break;
            case 2 : 
                ao.push({"sWidth": "100px"});
                break;
            default :
                ao.push({"sWidth": "25px"});
                break;
        }
    });
    return ao;
}

$(document).ready(function () {
    var table = $('#table').dataTable({
        aoColumns: aoColumns()
    });
});

通过使用这种方法,无论表有 1、3 还是 1000 列,数据表都将正确初始化。

如果您想根据每个列标题而不是索引来评估列宽,则需要稍微更改 aoColumn 函数:

function aoColumns() {
    var ao = [];
    $("#table th").each(function(i, th) {
        var caption=$(th).text();
        switch (caption) {
            case 'A' : 
                ao.push({"sWidth": "50px"});
                break;
            case 'B' : 
                ao.push({"sWidth": "100px"});
                break;

            /*...
            and so on
            ...*/

            default :
                ao.push({"sWidth": "25px"});
                break;
        }
    });
    return ao;
}

关于jquery - 数据表: fixed width for selected columns only,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18232184/

相关文章:

jsf - 从 Facelets 中向数据表行添加最后一行

datatables - 单击行获取数据对象

css - DataTables 按钮不在窄屏幕上居中

javascript - 不能在 DataTable 上定义超过 9 个列

javascript - 单击第二个下拉黑框时应保持可见

c# - 如何从简单的 DataTable 创建 DataGridViewComboBoxColumn

javascript - 导出按钮 数据表

javascript - Jquery 试图找到特定的父 div

javascript - 滚动到顶部或底部后的简单效果

jquery - 拖动时调整 JQuery Draggable 元素的包含父元素的大小