使用Javascript捕获输入和提供输出

时间:2015-10-24 04:07:42

标签: javascript input output

我终于开始学习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"/>

1 个答案:

答案 0 :(得分:3)

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是附加到窗口对象的,顺便使用函数中的vars就不那么容易混淆了。