JavaScript 中的 Enter 键按下事件?
javascriptweb developmentobject oriented programming更新于 2025/4/20 4:28:17
对于 ENTER 键按下事件,您可以调用一个函数 −
onkeypress="yourFunctionName"
Use the ENTER’s keycode 13.
示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fontawesome/ 4.7.0/css/font-awesome.min.css"> </head> <body> <input id="enterDemo" type="text" onkeypress="return enterKeyPressed(event)" /> <script> function enterKeyPressed(event) { if (event.keyCode == 13) { console.log("Enter key is pressed"); return true; } else { return false; } } </script> </body> </html>
要运行上述程序,请将文件名保存为"anyName.html (index.html)",然后右键单击该文件。在 VS Code 编辑器中选择"使用 Live Server 打开"选项。
输出
将产生以下输出 -

按下 ENTER 键后,控制台上将显示以下输出 -

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/
打印
下一节:如何使用 JavaScript 禁用按 Enter 键时 <input type="time"> 的默认行为? ❯❮ 上一节:如何将本地 json 文件数据导入到我的 JavaScript 变量中?

