效果體驗:https://hovertree.com/texiao/jquery/19/
表單中一連串的輸入欄位,若只能靠 Tab 鍵切換會有點麻煩。透過監聽 Enter 鍵並主動把焦點移到下一個輸入框,操作起來會順手很多。
用 keypress 事件取得按鍵碼,13 就是 Enter。接著用 nextAll() 找出後方所有同類元素,再用 eq(0) 取最靠近的那一個並聚焦:
$(function () {
$("#tabhovertree0").focus();
$("input[type='text']").on("keypress", function (event) {
var keycode = event.keyCode;
if (keycode == '13') { // 按下的是 Enter 鍵
$(this).nextAll("input[type='text']").eq(0).focus();
}
})
})
為什麼不直接寫 $(this).next().next().focus()?因為元素之間夾著 <br />,第一個 next() 只會拿到換行標籤,必須再取一次才是輸入框。這種寫法只要結構一改就會出錯,而 nextAll(...).eq(0) 直接過濾出目標元素,更穩健。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>jQuery實現按回車鍵跳轉到下個文本框 - 何問起</title>
<meta charset="utf-8" />
<script src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
</head>
<body>
<div>
<h2>jQuery實現文本框按回車鍵跳轉到下個文本框 何問起</h2>
效果如下,請按回車鍵,效果與Tab鍵相同:<br />
<input type="text" id="tabhovertree0" value="請按回車鍵" /><br />
<input type="text" id="tabhovertree1" value="請按回車鍵" /><br />
<input type="text" id="tabhovertree2" value="請按回車鍵" /><br />
<input type="text" id="tabhovertree3" value="請按回車鍵" /><br />
</div>
<script>
$(function () {
$("#tabhovertree0").focus();
$("input[type='text']").on("keypress", function (event) {
var keycode = event.keyCode;
if (keycode == '13') {
$(this).nextAll("input[type='text']").eq(0).focus();
}
})
})
</script>
</body>
</html>
本效果在 IE、Firefox、Chrome 等多種瀏覽器下均可正常運作。