我终于可以开始学习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"/>
最佳答案
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的方式,可以减少混乱。