javascript - 聚焦 NodeList 元素

标签 javascript html typescript nodelist

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/

相关文章:

javascript - NGXS 在 setState 中传播状态

javascript - 如何显示图像(img)或pdf(iframe)?

javascript - Ajax请求传递参数失败

javascript - 使用不同页面的服务而不显示它

javascript - 定义 HTML 类来表示多个 HTML 类

javascript - 替代 JSON.parse() 以保持小数精度?

javascript - 绘制星爆 - basil.js

html - CSS :target random #keyword, 用相同的 div 做一些事情

html - 沿路径发出动画 SVG

TypeScript 泛型 : infer key of key-value return type from function argument