简体   繁体   English

如何在Javascript中将焦点添加到childNodes

[英]How add focus to childNodes in Javascript

I'm trying to create a navigation in a UL Html Element. 我正在尝试在UL Html元素中创建导航。

I've done this : 我已经做到了:

let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name);
if (arg.keyCode == 40) { // down arrow
    if (this.arrowPosition < htmlUL.childNodes.length)
        this.arrowPosition++;
    console.log(htmlUL.childNodes[this.arrowPosition]);

} else if (arg.keyCode == 38) { //up arrow

    if (this.arrowPosition >= 2)
        this.arrowPosition--;

    console.log(htmlUL.childNodes[this.arrowPosition]);
}

In the console, I see the correct data when I press UP and DOWN. 在控制台中,按UP和DOWN可以看到正确的数据。

BUT I can't make a htmlUL.childNodes[this.arrowPosition].focus() : Property 'focus' does not exist on type 'Node' 但是我无法创建htmlUL.childNodes[this.arrowPosition].focus()Property 'focus' does not exist on type 'Node'

How can I focus on my childNodes Element? 如何关注我的childNodes元素? Thanks 谢谢

You have to cast the child element to type HTMLElement : 您必须转换子元素以输入HTMLElement

const id = `autocomplete_ul_${this.name}`;
const htmlUL = document.getElementById(id) as HTMLElement;

if (arg.keyCode === 40) { // down arrow
    if (this.arrowPosition < htmlUL.childNodes.length) {
      this.arrowPosition++;
    }
} else if (arg.keyCode === 38) { //up arrow
    if (this.arrowPosition >= 2) {
      this.arrowPosition--;
    }
}
const child = htmlUL.childNodes[this.arrowPosition] as HTMLElement;
child.focus();

OT: You tagged you question with the tag Angular , therefore you should get the list element the angular-way using the ViewChild decorator instead of using document.getElementById . OT:您用标签Angular标记了问题,因此应该使用ViewChild装饰器而不是document.getElementById来使列表元素成角度

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM