javascript - 除了第一个字段外,每个按键事件都会创建新元素
问题描述
我创建了一个网页,其中有一个文本字段。只要您enter在输入文本字段中按下键,<input type="text">
就会创建一个新的。对于第一个领域,它工作得非常好。但是,在新创建的字段中,当我按下任何键(甚至不是enter键)时,都会创建一个新元素。enter仅当按下键时才应创建新字段。
基本上,我的问题是在创建的新文本字段中,当我按任意键时,会创建一个新字段。我究竟做错了什么?我附上了一个代码片段来澄清我想问的问题:
function newlist(event) {
if (event.keyCode === 13) {
var todomain = document.getElementById("todomain");
var newList = document.createElement("input");
newList.type = "text";
newList.className = "todolist";
newList.onkeyup = function() {
newlist(event)
};
todomain.appendChild(newList);
}
}
.todomain {
width: 100%;
height: 92%;
position: absolute;
background-color: white;
top: 0;
left: 0;
}
.todolist {
width: 100%;
height: 5%;
background-color: #e0e0e0;
}
<!DOCTYPE html>
<html>
<body>
<div class="todomain" id="todomain">
<p>Press the enter key in the first text field, and a new field is created. However, pressing any key in the new elements creates another field. Only the enter key should create an element.</p>
<input type="text" class="todolist" onkeyup="newlist(event)">
</div>
</body>
</html>
解决方案
您已将第一个输入字段的“事件”参数传递给所有其他输入字段 keyup 事件方法。您需要传递各个字段的事件参数。
newList.onkeyup = function(e) {
newlist(e)
};
希望这能解决您的问题。
function newlist(event) {
if (event.keyCode === 13) {
var todomain = document.getElementById("todomain");
var newList = document.createElement("input");
newList.type = "text";
newList.className = "todolist";
newList.onkeyup = function(e) {
newlist(e)
};
todomain.appendChild(newList);
}
}
<!DOCTYPE html>
<html>
<body>
<div class="todomain" id="todomain">
<p>Press the enter key in the first text field, and a new field is created. However, pressing any key in the new elements creates another field, which should not be there. Only the enter key should create an element.</p>
<input type="text" class="todolist" onkeyup="newlist(event)">
</div>
</body>
</html>
推荐阅读
- netsuite - 套件上的 Netsuite USAGE_LIMIT_EXCEEDED 错误
- mysql - 有没有办法按与其子记录关联的最早日期对父记录进行排序?
- laravel - 黄昏无法资产查看自己的示例测试
- ruby-on-rails - 检测文件类型并调整图像大小
- javascript - 有没有人成功地使用 react-testing-library 来测试 DraftJS Editor 组件上的更改事件?
- javascript - 在 Canvas HTML getSeconds() 中,有没有办法以 56 秒 56 分 28 小时运行时钟?
- dask - 如何在每个工作人员上延迟 dask 以允许顺序执行进程?
- php - 从 firebase Php 获取上个月的数据
- postgresql - 在将数据插入 Postgresql 表时遇到一些麻烦
- c# - 如何使用 Dev Express Office File API 在现有文档上插入工作表