今天要修复一个小bug,当发生点击事件,会显示表单,要让表单内部的input自动获得焦点。
我想当然给表单控件设置了autofocus属性,然而,没有生效。
查看了下mdn的信息:
autofocus HTML5
This Boolean attribute lets you specify that a form control should have input focus when the page loads, unless the user overrides it (e.g. by typing in a different control). Only one form element in a document can have the autofocus attribute, which is a Boolean. It cannot be applied if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control). Note that the focusing of the control may occur before the firing of the DOMContentLoaded event.
为何我的修改没有效果?
因为我的页面列表是ajax请求数据生成的,而autofocus是在页面加载的时候就确定一个表单控件是否获取焦点。
Note that the focusing of the control may occur before the firing of the DOMContentLoaded event.
我的input标签是在页面加载完成之后才添加到dom中的;所以设置的autofocus没有生效。
最后还是老老实获取表单元素,添加focus事件。