2016-09-29 87 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);