【发布时间】:2019-11-08 17:54:42
【问题描述】:
我正在尝试做类似于https://inimino.org/~inimino/blog/javascript_live_text_input 的事情,当用户在字段中输入时,他们的输入会在另一个元素上直观地显示。
我遇到的问题是他的示例只是调用所有输入,但我有两个特定的字段要为此执行此操作,每个字段都有自己的 ID 和相应的目标。作为一个新手,不知道我会如何做到这一点。此外,他的票包括颠倒所写的内容和计算字符,这两个我都不需要。
他的 JS:
* one to set the content of an element.
*/
function reverse(s){return s.split('').reverse().join('')}
function set(el,text){
while(el.firstChild)el.removeChild(el.firstChild);
el.appendChild(document.createTextNode(text))}
/* setupUpdater will be called once, on page load.
*/
function setupUpdater(){
var input=document.getElementsByTagName('input')[0]
, reversed=document.getElementById('reversed')
, count=document.getElementById('charCount')
, orig=document.getElementById('original')
, oldText=input.value
, timeout=null;
/* handleChange is called 50ms after the user stops
typing. */
function handleChange(){
var newText=input.value;
if (newText==oldText) return; else oldText=newText;
set(reversed, reverse(newText));
set(count, 'You entered '+newText.length+' characters.');
set(orig, newText);
}
/* eventHandler is called on keyboard and mouse events.
If there is a pending timeout, it cancels it.
It sets a timeout to call handleChange in 50ms. */
function eventHandler(){
if(timeout) clearTimeout(timeout);
timeout=setTimeout(handleChange, 50);
}
input.onkeydown=input.onkeyup=input.onclick=eventHandler;
}
setupUpdater();
document.getElementsByTagName('input')[0].focus();
【问题讨论】: