按下输入时从表单写入div

时间:2015-06-24 03:08:17

标签: javascript html

我试图建立一个像网站这样的终端。我以前工作过,然后愚蠢地删除了一些代码,使整个事情停止工作。我有html,css和javascript文件。我已经检查过输入是否正常,if语句是否正常工作。我真的不知道该怎么做。

HTML:

<html>
  <head>
    <link href="cli.css" rel="stylesheet">
    <script src="cli.js"></script>
  </head>

  <body>
    <div id="console"></div>

    <form>
      <input type="text" id="input" onkeypress="checkKey()">
    </form>  
  </body>
</html> 

JS:

var input=""
function checkKey(){
  var code = event.keyCode;
  if(code == 13) {
    input = document.getElementById("input").value;

    if (input=="help") {
      document.getElementById("console").innerHTML="<p>HELP GOES HERE</p>";
      alert(input)

    } else {
      document.getElementById("console").innerHTML="<p> Invalid command type help for list of commands</p>";
    }
  }
}

function writeToConsole(whatToWrite) {
  document.getElementById("console").innerHTML="<p>"+whatToWrite+"</p>";
}

var objDiv = document.getElementById("console");
objDiv.scrollTop = objDiv.scrollHeight;

CSS:

body{
  background:black;
  color:green;
}
div#console{
  outline: 1px solid white;
  height: 90%;
  width: 100%;
  overflow: scroll;
  color:green;
}
input{
  outline: 1px solid white;
  width: 100%;
  background: black;
  color: green;
  height: 10%;
  font-size: 20pt;
}

1 个答案:

答案 0 :(得分:0)

由于输入位于表单内,因此输入键会导致提交事件,因此要防止它在输入键的情况下从keypress事件处理程序返回false。

此外,您必须将event对象从内联处理程序传递给处理程序方法。

同样objDiv.scrollTop = objDiv.scrollHeight;将导致错误,因为您的脚本已加载到标头中(因为在执行它时尚未创建dom元素),因此将其移至窗口加载处理程序。

<div id="console"></div>
<form>
    <input type="text" id="input" onkeypress="return checkKey(event)" />
</form>

然后

var input = "";

function checkKey(event) {
    var code = event.keyCode;
    if (code == 13) {
        input = document.getElementById("input").value;

        if (input == "help") {
            writeToConsole("<p>HELP GOES HERE</p>");
            alert(input)
        } else {
            writeToConsole("<p> Invalid command type help for list of commands</p>");
        }

        //need to return false as the form will get submitted else
        return false;
    }
}

function writeToConsole(whatToWrite) {
    document.getElementById("console").innerHTML = "<p>" + whatToWrite + "</p>";
}

//need to execute it after the dom is loaded
window.onload = function () {
    var objDiv = document.getElementById("console");
    objDiv.scrollTop = objDiv.scrollHeight;
}

演示:Fiddle