我有一个表,其列数不固定。但是,前 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/