核心代碼
$("#txtLoginPwd").keydown(function(e) {
if (e.which === 13) { // 13 = Enter 鍵
UserLogin();
}
});
關鍵點
- 使用
keydown 而非 keypress:keypress 在某些瀏覽器不觸發 Enter
e.which:jQuery 正規化的鍵碼,跨瀏覽器相容
- 在表單中按 Enter 可能觸發預設提交,必要時加
e.preventDefault()
完整表單範例
<form id="loginForm">
<input type="text" id="txtLoginId" placeholder="帳號" />
<input type="password" id="txtLoginPwd" placeholder="密碼" />
<button type="button" id="btnLogin">登入</button>
</form>
<script>
$("#txtLoginPwd, #txtLoginId").keydown(function(e) {
if (e.which === 13) {
e.preventDefault(); // 防止表單預設提交
$("#btnLogin").click(); // 觸發登入按鈕
}
});
$("#btnLogin").click(UserLogin);
function UserLogin() {
// 登入邏輯
}
</script>
現代原生替代
document.getElementById("txtLoginPwd").addEventListener("keydown", function(e) {
if (e.key === "Enter") { // 使用 key 而非 keyCode/which
e.preventDefault();
UserLogin();
}
});