数据表:通过循环动态创建列属性

DataTables: Creating column properties dynamically through a loop

本文关键字:创建 属性 动态 循环 数据表      更新时间:2023-09-26

我已经成功实现了DataTables (version 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个性质。由于我想在多个表中使用我的代码,但是具有不同数量的列,我希望通过基于列数量的循环动态创建此代码块。

这通常是可能的吗?有人可能有解决方案吗?任何帮助都是感激的!!

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