使用DOM - JavaScript组织表中的元素

时间:2016-05-14 15:01:33

标签: javascript dom

此代码是创建表

Recordset

喜欢这个图片1

enter image description here

var table = document.createElement("table"); if ((lines > 0) && (columns> 0)) { var tbody = document.createElement("tbody"); var tr, td; for (var i = 0; i < lines; i++) { tr = document.createElement("tr"); for (var j = 0; j < columns; j++) { td = document.createElement("td"); tr.appendChild(td); } tbody.appendChild(tr); } table.appendChild(tbody); document.body.appendChild(table); class Panel putAndShowEquipment

function

我想做这个图像2

enter image description here

如果我做的话,我可以做,

function Panel(id, line, column) {
  this.id = id;
  this.lines = line;
  this.columns = column;
  this.equipments = [];
  for(var i = 0; i < lines; i++{
      this.equipments[i] = [];
  }

}

Panel.prototype.putAndShowEquipment = function(line, column, equipment) {
  if ((line >= 0) && (line < this.lines) 
     && (column >= 0) && (column < this.columns) 
     && ((equipament === void 0) || (equipament instanceof Equipament))) {
    this.equipaments[line][column] = equipament;
    if (equipament) {
      equipament.show(this.cell(line, column));
    } else {
      (new View()).show(this.cell(line, column));
    }
  }
  return this;
}

但是我尝试使用//panel with 4 lines and 4 columns to 16 equipments (new Panel("panel",4,4)) .putAndShowEquipment (0, 0, new Equipament()) .putAndShowEquipment (0, 1, new Equipament()) .putAndShowEquipment (1, 0, new Equipament()) .putAndShowEquipment (1, 1, new Equipament()) .putAndShowEquipment (2, 0, new Equipament()) .putAndShowEquipment (2, 1, new Equipament()) ... ; 创建linescolumns并添加了设备,我认为可能有限制时为四列,更改为另一行,我已经准备好了,现在只是一个计算问题

for

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

鉴于您的更新问题,您似乎只需要将平面数组转换为矩形数组,方法是将平面this.equipaments数组的每个成员传递到构造函数中。

如果是这种情况,并且假设lines * columns的数量等于this.equipaments.length,则代替if语句,您只需要计算来自ij的索引。

// lines * columns === this.equipaments.length

for (var i = 0; i < lines; i++) {
  for (var j = 0; j < columns; j++) {
    panel.putAndShowEquipment(i + 1, j, this.equipaments[(i * columns) + j]);
  }
}

由于每行的列数相同,我们将当前行号乘以总列数,然后添加当前列号。