【问题标题】:Replace specific <p> with text from specific input onkeyup用特定输入 onkeyup 中的文本替换特定 <p>
【发布时间】: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();

【问题讨论】:

    标签: input onkeyup


    【解决方案1】:

    能够找到一个简单的答案:

    <script>
    
        var inputBox = document.getElementById('form');
    
        inputBox.onkeyup = function(){
            document.getElementById('text-element').innerHTML = inputBox.value;
        }
        </script>
    

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2012-02-07
      • 2018-03-24
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-12-17
      相关资源
      最近更新 更多