回車鍵是最常被使用的按鍵之一,因此「按下回車就執行某段程式」是很典型的互動需求。本文透過一個小實例,示範如何用 jQuery 監聽回車鍵並做出反應。
程式碼如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.linuxidc.com/" />
<title>監聽回車鍵範例</title>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){
$('input:text:first').focus();
var $inp=$('input');
$inp.keypress(function(e){
var key=e.which;
if(key==13){
$(this).css("color","red");
}
})
})
</script>
</head>
<body>
<input type="text" value="第一個輸入框"/>
<input type="text" value="第二個輸入框"/>
<input type="text" value="第三個輸入框"/>
</body>
</html>
這裡的關鍵是 keypress 事件搭配 e.which 判斷按下的按鍵碼——回車鍵對應的數字是 13。當使用者在某個文字框中按下回車,該文字框的文字便會變成紅色。
除了監聽回車,同样的手法也能用來判斷其他按鍵,例如空白鍵(32)、Esc(27)等,只要替換對應的 key code 即可,非常靈活。