2015-06-24 25 views
0

我正在嘗試使網站等終端。我以前工作過,然後愚蠢地刪除了一些使整個事情停止工作的代碼。我有HTML,CSS和JavaScript文件。我已檢查輸入是否正在工作,並且if語句正在工作,他們是。我真的不知道發生了什麼。當輸入被按下時從表單寫入div

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; 
} 

回答

0

由於輸入的是一個形式中,回車鍵導致一個提交事件,所以以防止在輸入密鑰的情況下從按鍵事件處理程序返回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

+0

你缺少'event' .... – epascarello

+0

@epascarello是感謝....使用Chrome的......但在休息FF –

相關問題