AddEventListener for multiple elements does not work with“focus”事件 [英] AddEventListener for multiple elements doesn't work with "focus" event

查看:88
本文介绍了AddEventListener for multiple elements does not work with“focus”事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有几个我想要的文本字段添加一个EventListener。
我把它们放在一个类中,并将EventListener添加到这个类中。
当选择事件是点击时,Everyhing可以完美工作。但是,当我将其改为专注时,没有任何反应。这是为什么?



这个工作:

  document.getElementById('parent') .addEventListener('click',emptyField,false); 

这并不是:

  document.getElementById('parent')。addEventListener('focus',emptyField,false); 

文字栏位:

  function emptyField(e){var clicked = e.target;如果(clicked.value == clicked.name){clicked.value =''; if(clicked.id =='password'){clicked.type ='password'; }}}  

; < input type =textname =USERNAMEid =usernamevalue =USERNAME>< br> < input type =textname =PASSWORDid =passwordvalue =PASSWORD>< br>< / class> querySelectorAll()

$ c>将返回所有输入 s:

  var fields = document.querySelectorAll('#parent input'); 

并使用循环将 focus 事件添加到每个字段:

  for(var i = 0; i< fields.length; i ++){
fields [ i] .addEventListener('focus',emptyField,false);
}

希望这有助于您。


I'm guessing I have a basic error in thinking but I just can't get around it.

I have a couple of text fields which I want to add an EventListener to. I put them all in one class and added the EventListener to this class. Everyhing works perfect when event of choice is "click". But when I change it to "focus" nothing happens. Why is that?

this works:

document.getElementById('parent').addEventListener('click', emptyField, false);

this doesn not:

document.getElementById('parent').addEventListener('focus', emptyField, false);

text fields:

function emptyField(e){
    var clicked = e.target;
	if (clicked.value == clicked.name)  {
		clicked.value='';
		
		if (clicked.id=='password') {
			clicked.type='password';
		}
	}	
}

<class id="parent">
	<input type="text" name="USERNAME" id="username" value="USERNAME"><br>
	<input type="text" name="PASSWORD" id="password" value="PASSWORD" ><br>
</class>

解决方案

I think you have to use querySelectorAll() that will return all the inputs :

var fields = document.querySelectorAll('#parent input');

And use loop to attach focus event to every field :

for (var i = 0; i < fields.length; i++) {
    fields[i].addEventListener('focus', emptyField, false);
}

Hope this helps.

这篇关于AddEventListener for multiple elements does not work with“focus”事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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