如何在Dart中向TableElement添加行?

Les*_*iak 6 html dart

我正在玩Dart,我正在尝试创建一个带有标题和tbody中的一行的新TableElement.

  TableElement table = new TableElement();

  Element head = table.createTHead();
  TableRowElement headerRow =  table.tHead.insertRow(-1);
  headerRow.insertCell(0).text = "9";
  headerRow.insertCell(1).text = "aaa";
  headerRow.insertCell(2).text = "bbb";
  headerRow.insertCell(3).text = "ccc";

  var tBody = table.createTBody();
  TableRowElement newLine = table.insertRow(-1); // add at the end
  newLine.insertCell(0).text = "9";
  newLine.insertCell(1).text = "aaa";
  newLine.insertCell(2).text = "bbb";
  newLine.insertCell(3).text = "ccc";
Run Code Online (Sandbox Code Playgroud)

不幸的是,这两行最终都出现在thead部分.最重要的是,如果我只离开

  TableElement table = new TableElement();

  var tBody = table.createTBody();
  TableRowElement newLine = table.insertRow(-1); // add at the end
  newLine.insertCell(0).text = "9";
  newLine.insertCell(1).text = "aaa";
  newLine.insertCell(2).text = "bbb";
  newLine.insertCell(3).text = "ccc";
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,该行到达tbody部分.有任何想法吗?Dart SDK 9474.

Mat*_*t B 2

在您的示例中,您将第一行直接添加到您创建的表标题中。但是第二行,您尝试直接添加到表中(而不是添加到 TBody 中)

请尝试以下操作:

TableElement table = new TableElement();

// ... See below ...

var tBody = table.createTBody();
TableElement newLine = tBody.insertRow(-1);
newLine.insertCell(0).text = "9";
newLine.insertCell(1).text = "aaa";
newLine.insertCell(2).text = "bbb";
newLine.insertCell(3).text = "ccc";
Run Code Online (Sandbox Code Playgroud)

正如评论中提到的,目前 dart:html 库不支持表头元素。因此,需要做一些解决办法。创建表头可以使用以下内容:

Element head = table.createTHead();
TableRowElement headerRow =  table.tHead.insertRow(-1);
var cell = new Element.tag('th');
cell.text = '9';
headerRow.insertAdjacentElement('beforeend', cell);
cell = new Element.tag('th');
cell.text = 'aaa';
headerRow.insertAdjacentElement('beforeend', cell);
cell = new Element.tag('th');
cell.text = 'bbb';
headerRow.insertAdjacentElement('beforeend', cell);
cell = new Element.tag('th');
cell.text = 'ccc';
headerRow.insertAdjacentElement('beforeend', cell);

// ... See above ...
Run Code Online (Sandbox Code Playgroud)

但请注意,insertAdjacentElement 不适用于 Firefox(因为他们选择不实现该 JavaScript 方法)。另一种方法是使用:

headerRow.nodes.add(cell);
Run Code Online (Sandbox Code Playgroud)

请注意,这是一种解决方法,不允许以与 insertCell 相同的方式进行索引,并且需要更多的工作来单独创建单元格。这提供了一种解决方法,以解决注释中列出的两个错误。