如何将触发键添加到我的 javascript 项目

How to add trigger key to my javascript project

当我向输入区添加内容时,如何将触发键添加到我的按钮?

我的代码:

let animals = [];

function add() {
  let addAnimal = document.getElementById("enter").value;
  animals.push(addAnimal);
  let openList = "<ul>";
  let text = "";
  let closeList = "</ul>"
  
  for (i = 0; i < animals.length; i++) {
    text += "<li>" + animals[i] + "</li>";
  }
  
  document.getElementById("demo").innerHTML = openList + text + closeList;
}
<input id="enter" />
<button onclick="add()">Submit</button>

要在键盘事件上添加事件侦听器,您可以使用 keydown 事件,然后根据 keyCodes

过滤事件

这里是一个按下回车键时工作的例子:

let animals = [];

function add() {
  let addAnimal = document.getElementById("enter").value;
  animals.push(addAnimal);
  let openList = "<ul>";
  let text = "";
  let closeList = "</ul>"
  
  for (i = 0; i < animals.length; i++) {
    text += "<li>" + animals[i] + "</li>";
  }
  
  document.getElementById("demo").innerHTML = openList + text + closeList;
}

function keyCallback(event) {
  if(event.key === "Enter") {
    add();
  }
}

addEventListener("keydown", keyCallback);
<input id="enter" />
<button onclick="add()">Submit</button>

<div id="demo"></div>