在 Dart 中,element.html(" ") 必须出现在 body 标签的上下文中吗?

In Dart must element.html(" ") occur within the context of a body tag?

TableElement table = new TableElement();
document.body.children.add(table);
table.children.add(new Element.html("<tr><td>test</td></tr>"));

以上代码片段returns错误:"Uncaught Bad state: No element"。阅读 DartLang 网站上的 API 文档,这是因为在使用 Element.html(" ") 构造函数时,"the HTML fragment is parsed as if it occurred within the context of a <body> tag"。因此,我们需要这样写:

new Element.html("<table><tr><td>test</td></tr></table>")

然而,阅读 "dart in action" Chris Buckett 在构建 table 时使用了完全相同的语法。

有什么变化还是我误解了什么?

这是一个浏览器"feature"。 <tr> 元素不能单独存在,当它找到一个时,就会从 HTML 中删除。

new Element.html() 的文档说

Creates an HTML element from a valid fragment of HTML.

或者您可以使用

  table.append(
      new TableRowElement()..append(new TableCellElement()..text = 'test'));

DartPad example