简体   繁体   English

对不同的DOM元素使用相同的功能

[英]Using the same function for different DOM elements

I have input and text boxes which have different placeholders like "number of reps", "time needed in secs" etc. 我有输入和文本框,它们具有不同的占位符,例如“代表次数”,“以秒为单位的时间”等。

<input type="text" id="sets" placeholder="Number of sets">
<textarea id="textarea" placeholder="write"></textarea>

I have built a click event so that whenever any box is clicked, its placeholder becomes blank so user inputs a value like so: 我建立了一个click事件,以便无论何时单击任何框,其占位符都将变为空白,因此用户输入的值如下所示:

textarea.addEventListener("click",checkInput);
sets.addEventListener("click",checkInput);

function checkInput(e){
  e.currentTarget.placeholder="";
} 

^^made a single function that can be used for both textarea and sets ^^做了一个可以同时用于文本区域和集合的函数

How can I get the placeholder back if the user clicks a box but doesn't type in a value and moves on to another item (blur event) by using a single function for all the items like so: 如果用户单击一个框但没有输入值并通过对所有项使用单个函数 ,则移至另一项(模糊事件) 我如何找回占位符, 如下所示:

textarea.addEventListener("blur",originalValue);
reps.addEventListener("blur",originalValue);

function originalValue(e){
    e.currentTarget.placeholder= default value/original value;
}

Try out this textbox 试用此文本框

 <input type="text" placeholder="Enter a value"> 

As you can see there is no code whatsoever , and it does exactly what you want; 如您所见, 没有任何代码 ,它可以完全满足您的要求。 if a user enters any text the placeholder is removed. 如果用户输入任何文本,则占位符将被删除。 If the user enters no text (or removes existing text) the placeholder is restored on blur. 如果用户不输入任何文本(或删除现有文本),则占位符会在模糊时恢复。

I seriously don't understand why you even began to write code around this! 我真的不明白,为什么您甚至开始围绕此编写代码!

If you just want to confuse your users, take a copy of the placeholder into the element before clearing it and restore it on blur. 如果只想让用户感到困惑,请在清除元素之前将占位符的副本复制到元素中,并在模糊时恢复它。

 textarea.addEventListener("click",checkInput); sets.addEventListener("click",checkInput); textarea.addEventListener("blur",restore); sets.addEventListener("blur",restore); function checkInput(e){ e.currentTarget.originalPlaceholder = e.currentTarget.placeholder e.currentTarget.placeholder=""; } function restore(e){ e.currentTarget.placeholder = e.currentTarget.originalPlaceholder; } 
 <input type="text" id="sets" placeholder="Number of sets"> <textarea id="textarea" placeholder="write"></textarea> 

I think this is a terrible idea FWIW! 我认为这是一个可怕的主意!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM