如何为表单内多个input元素绑定addEventListener focus事件
问题根因
document.getElementsByTagName('input')返回的是HTMLCollection类数组集合,不是单个DOM元素,集合本身没有addEventListener方法,直接调用不会生效。querySelectorAll返回的是NodeList类数组集合,同样无法直接调用该方法。- 你当前HTML的input标签上自带内联
onfocus="this.value=''"属性,触发focus时会先清空输入框值,会影响空值判断逻辑,可按需删除。
解决方案
方案1:遍历所有输入框单独绑定事件
适合页面input固定不会后续动态新增的场景:
// 获取页面所有input元素 const allInputs = document.querySelectorAll('input'); // 遍历逐个绑定focus事件 allInputs.forEach(inputEl => { inputEl.addEventListener('focus', function() { console.log("on focus"); // 去除首尾空格后判断是否为空 if (this.value.trim() === '') { alert('输入框内容不能为空'); } }) })
方案2:事件委托绑定(更推荐)
无需逐个绑定,后续动态新增的input也能自动触发逻辑,性能更优:
// 绑定到input的共同父元素form上 document.querySelector('.signUp').addEventListener('focus', function(e) { // 匹配触发事件的元素为input时执行逻辑 if (e.target.tagName.toLowerCase() === 'input') { console.log("on focus"); if (e.target.value.trim() === '') { alert('输入框内容不能为空'); } } // focus事件默认不冒泡,需要开启捕获阶段监听才能生效 }, true)
注意事项
如果保留input标签上的内联onfocus="this.value=''",触发focus时会先清空输入框内容,此时判断会始终命中空值逻辑,不符合需求的话直接删除该内联属性即可。
内容的提问来源于stack exchange,提问作者Matteo
相关产品推荐
相关产品推荐

