我已经成功实现了DataTables(版本1.10+)插件,我使用以下代码片段来定义列:
"columns": [
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]},
{"width" : "25%", "orderSequence": [ "desc", "asc" ]}
],
我现在的问题是我总是要为我在表格中使用的列数定义这些属性。在这里,我有4列,因此有4个属性。由于我想将我的代码用于多个表,但是使用不同数量的列,我希望在列数量的基础上通过循环动态创建这个代码块。
这一般是否可行,并且有人可能有解决方案吗?任何帮助表示赞赏!!
答案 0 :(得分:1)
function DataTableRowsDefs(columnCount)
{
// create the object and the 1st row
var cols = "columns" : [{"width" : "25%", "orderSequence": [ "desc", "asc" ]}];
// repeat for every element after that
for (i = 1; i < columnCount; i++) {
cols.columns.push({"width" : "25%", "orderSequence": [ "desc", "asc" ]});
}
// return array
return cols;
}
// call function:
DataTableRowsDefs(4);
修改强>
更正了冗余
function DataTableRowsDefs(columnCount) {
// create a single column
var column = {
"width": "25%",
"orderSequence": ["desc", "asc"]
};
// create the object and add the 1st column
var jsonColumns = {
"columns": [column]
};
// repeat for every column after that
for (i = 1; i < columnCount; i++) {
jsonColumns.columns.push(column);
}
// return array
return(jsonColumns);
}
// call function:
DataTableRowsDefs(4);