繁体   English   中英

JavaScript.focus() function 在文本字段中不起作用

[英]JavaScript .focus() function not working in a text field

我试图在以下表单字段上使用 .focus() 但没有成功。 该元素所在的div的tabindex为0。

<input class="form-control ng-pristine ng-valid ng-empty ng-touched" id="accessionNumber" type="text" name="filter.accessionNumber" ng-model="selectFields.accessionNumber" style="">

我正在使用以下内容:

document.getElementsByName("filter.accessionNumber")[0].focus()

我也尝试过使用“accessionNumber”ID 以及 .click .click() function 而不是.focus() function 的document.getElementById ,但到目前为止都没有用

谢谢!

简短回答:也许看看这篇文章

更长的答案:由于您使用的是 Angular,因此您应该使用支持此功能的框架功能: ViewChild

使其工作的步骤:

  1. 在您的组件中创建一个带有 ViewChild 注释的变量
  2. 在组件模板中用 ViewChild id 标记元素
  3. ngAfterViewInit中访问你的元素
this.myElement.nativeElement.focus();

暂无
暂无

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

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