目录

如何 - 触发按钮单击 Enter


使用 JavaScript 触发键盘 "enter" 上的按钮单击。


触发按钮单击 Enter

按输入字段内的 "Enter" 键来触发按钮:

示例

// Get the input field
var input = document.getElementById("myInput");

// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
  // If the user presses the "Enter" key on the keyboard
  if (event.key === "Enter") {
    // Cancel the default action, if needed
    event.preventDefault();
    // Trigger the button element with a click
    document.getElementById("myBtn").click();
  }
});
亲自试一试 »

提示:了解更多关于KeyboardEvent 键 属性在我们的 JavaScript 参考中。