如何使用 jQuery 得知在表單輸入中按下的按鍵?
要了解使用 jQuery 在表單輸入中按下哪個鍵,請使用 jQuery keydown 事件。您可以嘗試執行以下程式碼瞭解如何在表單輸入元素中檢測已按下的鍵 -
例項
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('#myinput').keydown(function(e) { var newkey = 'Key code = ' + e.which + ' ' + (e.ctrlKey ? 'Ctrl' : '') + ' ' + (e.shiftKey ? 'Shift' : '') + ' ' + (e.altKey ? 'Alt' : ''); $('#mykey').text(newkey); return false; }); }); </script> </head> <body> <form id="myform"> Press any key: <input id='myinput' type='text' /> </form> <div id='mykey'>The key you press is visible here with keycode.</div> </body> </html>
廣告