如何为Handsontable创建动态列?

时间:2013-04-24 07:17:59

标签: jquery handsontable

我正在使用Handsontable创建一个可以在web和excel之间复制/粘贴的网格,我尝试使用下面的代码并且工作正常:

  var first = true;
  var exampleGrid = $("#exampleGrid");
  exampleGrid.handsontable({
      rowHeaders: true,
      colHeaders: true,
      stretchH: 'all',
      minSpareCols: 0,
      minSpareRows: 0,
      height: 600,
      columns: [
      { data: "Id", title: "ID", type: "text" }, //'text' is default, you don't actually have to declare it
      { data: "Name", title: "Name", type: "text" },
      { data: "DisplayColor",
      title: "Display Color",
      type: 'autocomplete',
      source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"]
      },
      { data: "Description", title: "Description", type: 'text' },
      { data: "IsDeleted", title: "Is Deleted", type: 'checkbox' }
      ],
      colWidths: [400, 100, 60, 100, 50, 40, 40, 60], //can also be a number or a function
      contextMenu: false,
  });

现在我需要创建带有动态列的网格,我尝试用下面的函数替换列列表,但它不起作用:

    columns:
        function () {
            var cols = [];
            for (var i = 0; i < 1; i++) {
                var col = new Object();

                col.data = "Name";
                col.title = "Name" + i.toString();
                col.type = "text";
                cols[i] = col;
            }
            return cols;
        },

是否可以在Handsontable网格中创建动态列?以及如何做到这一点?

我是一名JavaScript初学者,所以请告诉我是否有任何错误,谢谢!

1 个答案:

答案 0 :(得分:12)

我自己解决了这个问题,函数不能直接在列定义中使用,但允许变量,所以下面的代码可以工作:

var dynamicColumns = [];
for (var i = 0; i < 366; i++) {
    var col = new Object();
    col.data = "Name";
    col.title = "Name " + i.toString();
    col.type = "text";
    dynamicColumns.push(col);
}

skillGrid.handsontable({
    // ...
    columns: dynamicColumns,
    // ...