2016-09-29 89 views
0

我已成功实现,其中我用下面的代码来定义的列数据表(版本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个属性。由于我想将我的代码用于多个表,但是有不同数量的列,我希望根据列的数量通过循环动态创建此代码块。

这是一般可能的,是否有人可能有解决方案?任何帮助表示赞赏!

回答

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);