Javascript 在DOM更改时向所有输入元素添加EventListener
当文档完成时,我正在执行以下操作Javascript 在DOM更改时向所有输入元素添加EventListener,javascript,dom,Javascript,Dom,当文档完成时,我正在执行以下操作 var passwordInputs = document.querySelectorAll("input[type=password]"); for (index = 0; index < passwordInputs.length; ++index) { passwordInputs[index].addEventListener("focusin", activeWordsFocusIn); passwordInputs[index
var passwordInputs = document.querySelectorAll("input[type=password]");
for (index = 0; index < passwordInputs.length; ++index) {
passwordInputs[index].addEventListener("focusin", activeWordsFocusIn);
passwordInputs[index].addEventListener("focusout", activeWordsFocusOut);
}
var passwordInputs=document.querySelectorAll(“input[type=password]”);
for(索引=0;索引
这和预期的一样。但是,如果页面有一些额外的脚本修改DOM并添加更多的input
元素,那么它们就不会被钩住
如何为所有input
元素添加事件处理程序,甚至那些通过脚本/ajax添加到DOM的元素
<强>不是重复< <强> >我不认为这是一个重复的问题,它集中于检测DOM中的变化。我的问题集中在向所有
input
元素添加eventListener
,即使DOM发生了变化。我现在已经添加了我自己的答案。这是我发现有效的解决方案
function activeWordsFocusIn(e) {
if (isPassword(e)) {
console.log("focus in");
}
}
function activeWordsFocusOut(e) {
if (isPassword(e)) {
console.log("focus out");
}
}
function isPassword(e) {
var e = window.e || e;
if (e.target.tagName !== 'INPUT')
return false;
if (e.target.type !== 'password')
return false;
return true;
}
document.addEventListener('focusin', activeWordsFocusIn, false);
document.addEventListener('focusout', activeWordsFocusOut, false);
您可以使用事件委派将事件处理程序添加到输入的容器中。当容器内的元素触发事件时, 我们检查元素是否是选择器,如果是,则调用事件处理程序
constdelegate=(选择器)=>(cb)=>(e)=>e.target.matches(选择器)和&cb(e);
const inputDelegate=delegate('input[type=password]');
container.addEventListener('focusin',inputDelegate((el)=>console.log('focusin',el.target.name));
container.addEventListener('focusout',inputDelegate((el)=>console.log('focus out',el.target.name));
设置超时(()=>{
常量输入=document.createElement('input');
input.setAttribute('type','password');
setAttribute('name','input2');
container.append(输入);
}, 2000);代码>
这与使用JS的事件委派有关,然后检测DOM更改。清洁解决方案谢谢-chrome是否支持匹配项
?是的。它实际上有很好的支持。IE9甚至支持它(带有前缀)。。。什么是容器
对象?没有容器对象。它是对id为container
的div的引用。在html中使用id
时,将创建一个全局变量,用于id为的元素。长话短说——它就像一个自动的getElementById()
,是不使用ids的一个很好的理由。。。我想知道比我建议的答案有什么好处。你的看起来更干净,还有别的吗?