我正在尝试创建一个js控制台,我想做一个控制台事情,当您按下向上箭头时,它将放置您执行的最后一个命令。 所以我这样做了,但是idk为什么它不起作用:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="author" content="MightyCoderX">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Online Js Console</title>
<script src="main.js"></script>
<link rel="stylesheet" href="general.css">
</head>
<body>
<div class="input-container">
<div class="prompt">></div>
<input class="input">
</div>
<div class="output"></div>
</body>
</html>
JS
var input;
var output;
var cmdHistory = [];
window.onload = function()
{
input = document.querySelector(".input");
output = document.querySelector(".output");
input.onkeydown = function(e)
{
var currentIndex;
if(e.key == "Enter" && input.value)
{
var inputExp = document.createElement("p")
inputExp.id = "inputExp";
inputExp.innerHTML = "> " + input.value;
cmdHistory.push(input.value);
output.appendChild(inputExp);
var result = document.createElement("p");
result.id = "result";
output.appendChild(result);
try
{
result.innerHTML = "< " + eval(input.value);
}
catch(ex)
{
result.innerHTML = ex;
result.style.color = "red";
}
var topPos = result.offsetTop;
output.scrollTop = topPos;
currentIndex = cmdHistory.length-1;
console.log(currentIndex);
input.value = "";
}
console.log("Out " + currentIndex);
if(e.key == "ArrowUp")
{
if(currentIndex > -1)
{
console.log("In " + currentIndex);
input.value = cmdHistory[currentIndex];
currentIndex -= 1;
console.log("After " + currentIndex);
}
}
}
}
这是我的代码idk,我以为还可以,但是我显然认为它不起作用,但是如果按向上箭头,它将显示以下内容: Here it is my app
答案 0 :(得分:1)
只需将var currentIndex
移动到window.onload
函数之外。可能对您有用。
var input;
var output;
var cmdHistory = [];
var currentIndex;
window.onload = function()
{
input = document.querySelector(".input");
output = document.querySelector(".output");
input.onkeydown = function(e)
{
if(e.key == "Enter" && input.value)
{
var inputExp = document.createElement("p")
inputExp.id = "inputExp";
inputExp.innerHTML = "> " + input.value;
cmdHistory.push(input.value);
output.appendChild(inputExp);
var result = document.createElement("p");
result.id = "result";
output.appendChild(result);
try
{
result.innerHTML = "< " + eval(input.value);
}
catch(ex)
{
result.innerHTML = ex;
result.style.color = "red";
}
var topPos = result.offsetTop;
output.scrollTop = topPos;
currentIndex = cmdHistory.length-1;
console.log(currentIndex);
input.value = "";
}
console.log("Out " + currentIndex);
if(e.key == "ArrowUp")
{
if(currentIndex > -1)
{
console.log("In " + currentIndex);
input.value = cmdHistory[currentIndex];
currentIndex -= 1;
console.log("After " + currentIndex);
}
}
}
}
答案 1 :(得分:1)
更改此
var currentIndex;
到
var currentIndex = cmdHistory.length -1;