将JS函数和事件侦听器应用于多个html元素 [英] Applying JS function and event listener to multiple html elements
问题描述
我正在创建一个表单,下面对此进行了简化,以使您理解到这一点,JS代码是控制占位符;隐藏在焦点上并在模糊时再次出现,显然,这现在仅适用于id('Name')的输入.如何将这些功能应用于所有输入元素DRY,而无需为每个输入重复代码.
I am creating a form which I simplified below to get straight to the point, the JS code is to control the placeholder; hiding on focus and reappear on blur, obviously this now works for the input with id('Name') only. How do I apply these functions to all inputs elements DRY without repeating the code for each input.
var x = document.getElementById("Name");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);
function myFocusFunction() {
document.getElementById('Name').placeholder= '';
}
function myBlurFunction() {
document.getElementById('Name').placeholder= 'Name';
}
<div id='card'>
<input id='Name' type='text' placeholder='Name'/>
<input id='Age' type='text' placeholder='Age'/>
<input id='Sex' type='text' placeholder='Sex'/>
<input id='Occupation' type='text' placeholder='Occupation'/>
</div>
推荐答案
Array.from(document.getElementsByTagName("input")).forEach(input => {
input.addEventListener("focusin", focus);
input.addEventListener("focusout", blur.bind(input, input.placeholder));
});
function focus() {
this.placeholder = '';
}
function blur(placeholder) {
this.placeholder = placeholder;
}
<div id='card'>
<input id='Name' type='text' placeholder='Name' />
<input id='Age' type='text' placeholder='Age' />
<input id='Sex' type='text' placeholder='Sex' />
<input id='Occupation' type='text' placeholder='Occupation' />
</div>
使用this
关键字,您可以访问触发事件的对象.
Using the this
keyword you can access the object which the event was triggered on.
此外,您还需要以某种方式保留占位符,在上面的示例中,我使用了绑定函数,但是您可以选择自己的方式.
Also you need to preserve the placeholder somehow, in the example above I used bound function but you can chose your own way.
您还可以在此答案的版本2 中找到如何手动指定名称的示例.
You can also find an example how to specify names manually in revision 2 of this answer.
这篇关于将JS函数和事件侦听器应用于多个html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!