【问题标题】:getting value from input and displaying in a div从输入中获取值并在 div 中显示
【发布时间】:2017-03-27 06:22:56
【问题描述】:

我正在尝试获取输入的值并将其显示在其下的 div 中,同时用户正在键入。我想用香草js来做。没有 j 查询。

我的 HTML:

<div id="userInputBox">
<input id="inputText" type="text"      
placeholder="Enter your question" size = "50" onkeyup="myDisplay()"/>
</div>
<div class="displayQuestion"></div>

我的 JS:

var input = document.getElementById('inputText').value;
var showQuestion = document.getElementsByClassName('displayQuestion');
function myDisplay(e){
showQuestion.innerHTML = input;
}

【问题讨论】:

  • 请看下面
  • 我用className 回答了您的问题,但您已接受id 解决方案。请问可以知道原因吗?

标签: javascript html input vanilla-forums


【解决方案1】:

试试这个:

function myDisplay(e) {
  var input = document.getElementById('inputText').value;
  var showQuestion = document.getElementById('displayQuestion');
  showQuestion.innerHTML = input;
}
<div id="userInputBox">
  <input id="inputText" type="text"
placeholder="Enter your question" size = "50" onkeyup="myDisplay(this.value)"/>
</div>
<div id="displayQuestion"></div>
  

【讨论】:

    【解决方案2】:

    给你VannilaJS的方式,

    建议:把函数名myDisplay()改成有意义的名字,比如displayQuestion()

    var targetElm = document.getElementsByClassName('displayQuestion');
    var inputElm = document.getElementById('inputText');
    
    function myDisplay() {
      if(targetElm && targetElm.length > 0){
        targetElm[0].innerHTML = inputElm.value;
      }
    }
        <div id="userInputBox">
          <input id="inputText" type="text"      
          placeholder="Enter your question" size ="50" onkeyup="myDisplay()"/>
          </div>
        <div class="displayQuestion"></div>

    【讨论】:

    • @KashaCathy 我用className 回答了您的问题,但您已接受id 解决方案。请问可以知道原因吗?
    猜你喜欢
    • 2017-12-01
    • 2019-08-05
    • 1970-01-01
    • 2014-05-12
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-22
    相关资源
    最近更新 更多