首页 > 解决方案 > 除了第一个字段外,每个按键事件都会创建新元素

问题描述

我创建了一个网页,其中有一个文本字段。只要您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>

标签: javascripthtmlcss

解决方案


您已将第一个输入字段的“事件”参数传递给所有其他输入字段 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>


推荐阅读