[英]Typescript - How to iterate over a HTMLCollection
我是 typescript 的新手,我正在尝试遍历document.getElementsByClassName()
获得的 HTMLCollection。 我的代码是:
let tag_list = document.getElementsByClassName("...") as HTMLCollectionOf<HTMLLinkElement>;
for (const tag of tag_list) {
//do sth with tag.href
}
但事实证明“TS2495:类型'HTMLCollectionOf'不是数组类型或字符串类型。” 那么我能做些什么来防止这个错误呢?
HTMLCollectionOf<HTMLLinkElement>
不是数组,因此,您不能对其进行迭代。 因此,您需要使其成为数组
for (const tag of Array.from(tag_list)) {
希望这个帮助
如this SO answer所示,它依赖于编译。
tsconfig.json
:
{
"compileOnSave" : true,
"compilerOptions": {
"noImplicitAny" : true,
"target" : "ES2021",
"moduleResolution": "Node"
},
"exclude": [
"node_modules",
"dist"
]
}
以下代码编译并运行:
const tds = document.getElementsByTagName('td') as HTMLCollectionOf<HTMLTableCellElement>;
for( const td of tds ) {
Utils.onClick( td, ( event: UIEvent ) => this.place( event, 1, 1 ));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.