我希望网站在元素已填充时更改元素的类。因此,当用户 blur
离开输入字段时,程序会检查它是否具有任何值,如果是,则添加一个类。问题是将此行为传递给类集合中的每个元素。
var input = document.getElementsByClassName('input');
contentCheck = function(i){
if(input[i].value>0) input[i].classList.add('filled');
else input[i].classList.remove('filled');
};
for(var i=0; i<input.length; i++) {
input[i].addEventListener('blur',contentCheck(i));
}
这在重新加载页面后会起作用一次(如果缓存中有任何内容),但是 contentCheck()
应该在您每次离开焦点时触发。
最佳答案
您已经对该代码应用了一半的“closures in loops”解决方案,但您不需要循环闭包解决方案,只需在 contentCheck
中使用 this
> 并将它指定为处理程序(而不是调用它并使用其返回值作为处理程序):
var input = document.getElementsByClassName('input');
var contentCheck = function(){ // <== No `i` argument (and note the `var`)
// Use `this` here
if(this.value>0) this.classList.add('filled');
else this.classList.remove('filled');
};
for(var i=0; i<input.length; i++) {
input[i].addEventListener('blur',contentCheck);
// No () here -------------------------------------^
}
旁注:classList
有一个方便的 toggle
函数,它带有一个可选的标志:
var contentCheck = function(){
this.classList.toggle('filled', this.value > 0);
};
如果您需要“循环中的闭包”解决方案(同样,您不需要,但只是为了完整性),您需要contentCheck
返回 一个进行检查的函数:
var input = document.getElementsByClassName('input');
var makeContentCheckHandler = function(i){
return function() {
if(input[i].value>0) input[i].classList.add('filled');
else input[i].classList.remove('filled');
};
};
for(var i=0; i<input.length; i++) {
input[i].addEventListener('blur', makeContentCheckHandler(i));
}
请注意,为了清楚地说明它的作用,我更改了名称。
关于javascript - 每个对象的触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40375392/