NodeList
项没有 focus
方法。但是,我见过一些用字面意思 nodeList[index].focus()
编写的文章,这一定是不正确的,对吗?
我们如何聚焦 NodeList 中的元素?
let nodeList:NodeList = el.nativeElement.querySelectorAll('a');
...
nodeList[0].focus(); // Property 'focus' does not exist on type 'Node'
(nodeList[0] as HTMLElement).focus(); // doesn't work
最佳答案
NodeList
类型不够窄;您必须指定它是 HTMLElement
的节点列表s。您可以使用 NodeListOf<HTMLElement>
来执行此操作类型:
let nodeList: NodeListOf<HTMLElement> = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();
请注意,您也可以让编译器推断 nodeList
的正确类型。并避免必须显式键入它:
let nodeList = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();
关于javascript - 聚焦 NodeList 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68147147/