【问题标题】:Capturing Input and Providing Output with Javascript使用 Javascript 捕获输入并提供输出
【发布时间】:2016-01-23 16:55:28
【问题描述】:

我终于开始学习 Javascript;我正在尝试做一些简单的事情:在提供输出的同时捕获键盘输入。我得到键盘按下的半响应输出,但是一旦按下enter,我就无法在页面的输出部分附加一行输入。我做错了什么?

<script language="javascript">
    processCommand = function(cmd) {
        if (this.text == null) this.text = "";
        this.text = this.text + cmd + "<br>";
        document.getElementById("outputID") = this.text;
    }
    document.onkeydown = function(evt) {
        if (this.text == null) this.text = ""; 
        var keyChar = String.fromCharCode(evt.keyCode);
        this.text = this.text + keyChar;
        if (evt.keyCode == 13) {
            processCommand(this.text);
            this.text = "";
        }
        document.getElementById("input").innerHTML = this.text;
    };
</script>
<spad id="outputID"/><br>
<hr>
<spad id="input"/>

【问题讨论】:

  • 这是document.getElementById("outputID").innerHTML = this.text 不是document.getElementById("outputID") = this.text;
  • 我要做的第一件事是为document.getElementById("outputID") document.getElementById("input") 元素引入一个变量。无需在每次按键时查找它们

标签: javascript input output


【解决方案1】:

http://codepen.io/anon/pen/gavNOm

<script language="javascript">
 processCommand = function(cmd) {
    if (this.text == null) this.text = "";
    this.text = this.text + cmd + "<br>";
    outputID.innerHTML = this.text;
}
document.onkeydown = function(evt) {
    if (this.text == null) this.text = ""; 
    var keyChar = String.fromCharCode(evt.keyCode);
    this.text = this.text + keyChar;
    if (evt.keyCode == 13) {
        processCommand(this.text);
        this.text = "";
    }
    input.innerHTML = this.text;
   };
 </script>
 <span id="outputID"/><br>
<hr>
<span id="input"/>

id 附加到 window 对象上,顺便说一下,在函数中使用 var 就不会那么混乱了。

【讨论】:

  • this.text 在两个函数中都是两个独立的变量
  • 好的,感谢您的提示。现在我需要发现为什么processCommand 似乎只工作一次
猜你喜欢
  • 2010-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-17
  • 2017-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多