gil*_*t-v 0 html javascript innerhtml
我正在开发一个模拟控制台窗口的项目。当用户按下 Enter<input>键时,屏幕上会添加一个新的文本字段并聚焦。唯一的问题是之前<input>字段的值在此过程中丢失了。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src='script.js'></script>
</head>
<body>
<input type="text" class="console_window"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
var input;
function init() {
function keyup(e) {
switch(e.which) {
case 13:
document.body.innerHTML +=
"<input type='text' class='console_window'/>"
input = document.getElementsByClassName("console_window")[document.getElementsByClassName("console_window").length-1];
input.focus();
break;
}
}
document.addEventListener("keyup", keyup, false);
}
document.addEventListener("DOMContentLoaded", init, false);
Run Code Online (Sandbox Code Playgroud)
和小提琴。
另外,我不喜欢使用插件。
谢谢!
这是因为您正在重置页面的 html 标记...
您应该考虑使用 DOM 元素操作,而不是添加纯 HTML 文本:
var inp = document.createElement("input");
inp.className = "console_window";
inp.type = "text";
document.body.appendChild(inp);
inp.focus();
Run Code Online (Sandbox Code Playgroud)