[英]How to dynamically create a TypeScript table
Typescript doesnt seem to accept the standard syntax for creating a javascript table, so what is the appropriate method? Typescript似乎不接受创建javascript表的标准语法,那么适当的方法是什么? I was unable to find documentation concrning tables in TypeScript.
我无法在TypeScript中找到文档concrning表。
This is what I would expect to work: 这是我期望的工作:
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
That is a direct paste from W3schools javascript, however visual studio reports an error at table.insertRow(); 这是来自W3schools javascript的直接粘贴,但是visual studio在table.insertRow();
"Property 'insertRow' does not exist on type 'HTMLElement'" “类型'HTMLElement'上不存在'属性'insertRow'”
The same error ocors using this code: 使用此代码时出现相同的错误:
class ModuleTable {
table: HTMLTableElement;
private thead: HTMLElement;
private tbody: HTMLElement;
constructor() {
this.table = document.createElement('table');
this.thead = this.table.createTHead();
this.tbody = this.table.createTBody();
var row = this.thead.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML = "Module ID";
}
}
Should I use appendChildren with a new HTMLElement, representing a row to be added to the header? 我应该将appendChildren与新的HTMLElement一起使用,表示要添加到标题的行吗?
Try: 尝试:
var table: HTMLTableElement = <HTMLTableElement> document.getElementById("myTable");
var row = table.insertRow(0);
The reason is that Typescript does not know the exact type of document.getElementById()
, just that it returns a generic HTMLElement
. 原因是Typescript不知道
document.getElementById()
的确切类型,只是它返回一个通用的HTMLElement
。 You know it is a table, so you can cast it. 你知道它是一张桌子,所以你可以施展它。
After looking at Nikos response, this code ended up solving the issue. 在看了Nikos的回复之后,这段代码最终解决了这个问题。 Typescript table, created dynamicall, from code only
Typescript表,仅从代码创建的dynamicicall
class ModuleTable {
table: HTMLTableElement;
private thead: HTMLTableElement;
private tbody: HTMLTableElement;
constructor() {
this.table = document.createElement('table');
this.thead = <HTMLTableElement> this.table.createTHead();
this.tbody = <HTMLTableElement> this.table.createTBody();
var hrow = <HTMLTableRowElement> this.table.tHead.insertRow(0);
var cell = hrow.insertCell(0);
cell.innerHTML = "Module ID";
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.