ENTER 키에서 버튼을 트리거하는 코드는 다음과 같습니다 -
예시
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample, .result { font-size: 18px; font-weight: 500; color: red; } .result { color: blueviolet; } </style> </head> <body> <h1>Trigger a button on ENTER key</h1> Enter text<input type="text" class="sample" /> <button class="Btn">CLICK HERE</button> <div class="result"></div> <h3> Press enter in the above text field to trigger the button </h3> <script> let resultEle = document.querySelector(".result"); let sampleEle = document.querySelector(".sample"); sampleEle.addEventListener("keyup", (event) => { if (event.keyCode === 13) { event.preventDefault(); document.querySelector(".Btn").click(); } }); document.querySelector(".Btn").addEventListener("click", () => { resultEle.innerHTML ="Button has been clicked and text = " + sampleEle.value; }); </script> </body> </html>
출력
일부 텍스트를 입력하고 입력 필드에서 Enter 키를 누르면 -