DOM 更改时向所有 INPUT 元素添加事件监听器

4 javascript dom

目前,当文档完成时,我正在执行以下操作。

var passwordInputs = document.querySelectorAll("input[type=password]");

for (index = 0; index < passwordInputs.length; ++index) {
    passwordInputs[index].addEventListener("focusin", activeWordsFocusIn);
    passwordInputs[index].addEventListener("focusout", activeWordsFocusOut);
}
Run Code Online (Sandbox Code Playgroud)

这按预期工作。但是,如果页面有一些额外的脚本来修改 DOM 并添加更多input元素,那么它们就不会被挂钩。

如何为所有input元素添加事件处理程序,即使是那些通过脚本/ajax 添加到 DOM 的元素?

不是重复的我不认为这是重复的,因为这个问题检测 DOM中的变化,它专注于检测 DOM 中的变化。我的问题的重点是在DOM 更改时eventListener向所有input元素添加一个。我现在已经为此添加了我自己的答案。

Ori*_*ori 7

您可以使用事件委托将事件处理程序添加到输入的容器中。当容器内的元素触发事件时,我们检查该元素是否选择器匹配,如果匹配,则调用事件处理程序。

const delegate = (selector) => (cb) => (e) => e.target.matches(selector) && cb(e);

const inputDelegate = delegate('input[type=password]');

container.addEventListener('focusin', inputDelegate((el) => console.log('focus in', el.target.name)));

container.addEventListener('focusout', inputDelegate((el) => console.log('focus out', el.target.name)));

setTimeout(() => {
  const input = document.createElement('input');
  input.setAttribute('type', 'password');
  input.setAttribute('name', 'input2');
  
  container.append(input);
}, 2000);
Run Code Online (Sandbox Code Playgroud)
<div id="container">
  <input type="password" name="input1">
</div>
Run Code Online (Sandbox Code Playgroud)