为什么不让函数动态生成aoColumns
-array?
// 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 :
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;
}