DOM更改时将addEventListener添加到所有INPUT元素 [英] addEventListener to ALL INPUT elements when DOM changes

查看:417
本文介绍了DOM更改时将addEventListener添加到所有INPUT元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我正在完成文档。

At the moment I'm doing the following when the document is complete.

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

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

工作正常。但是,如果页面有一些其他脚本来修改DOM并添加更多 input 元素,则它们不会被钩住。

Which works as expected. However if the page has some additional script which modifies the DOM and adds more input elements then they are not hooked.

如何为所有 input 元素,甚至通过脚本/ ajax添加到DOM中的元素添加事件处理程序?

How can add event handlers for ALL input elements, even those added to the DOM thru script/ajax?

不是重复的,我不认为这是重复的,因为此问题检测DOM中的更改,该更改着重于检测DOM中的更改。我的问题集中在向所有 input 元素添加 eventListener ,即使DOM更改也是如此。此后,我现在对此添加了自己的答案。

Not a duplicate I don't consider this a duplicate as this question Detect Changes in the DOM which focuses on detecting changes in the DOM. My questions focus is on adding an eventListener to all input elements even when the DOM changes. I have since added my own answer to this now.

推荐答案

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

You can use event delegation to add an event handler to the container of the inputs. When an element inside the container triggers an event, we check if the element matches the selector, and if so, the event handler is called.

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);

<div id="container">
  <input type="password" name="input1">
</div>

这篇关于DOM更改时将addEventListener添加到所有INPUT元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆