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



我试图使用.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()

我也试过document.getElementById使用" accessessionnumber "ID以及.click()函数而不是.focus()函数,但到目前为止都没有工作

谢谢!

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

长一点的回答:既然你使用的是Angular,你应该使用框架的特性来启用它:

操作步骤:

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

最新更新