【问题标题】:Focus a NodeList element聚焦 NodeList 元素
【发布时间】:2021-06-27 00:28:20
【问题描述】:

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

【问题讨论】:

  • let nodeList: NodeListOf<HTMLElement> = ... 有效吗? (注意:你不能明确地输入 `nodeList,它应该被正确推断出来。)

标签: javascript html typescript nodelist


【解决方案1】:

NodeList 不是一个足够窄的类型;您必须指定它是HTMLElements 的节点列表。您可以使用 NodeListOf<HTMLElement> 类型执行此操作:

let nodeList: NodeListOf<HTMLElement> = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();

请注意,您也可以让编译器推断nodeList 的正确类型,而不必显式键入它:

let nodeList = el.nativeElement.querySelectorAll('a');
nodeList[0].focus();

【讨论】:

    猜你喜欢
    • 2016-07-19
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2015-04-30
    • 2012-02-27
    • 2017-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多