<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
var length = $(":input").length;
$(":input").keyup(function(e) {
var key = e.which;
if (13 == key) {
var index = $(":input").index(this);
var newIndex = index + 1;
if(length == newIndex)
{
newIndex = 0;
}
$(":input:eq(" + newIndex + ")").focus();
}
});
});
</script>
</head>
<body>
<form id="frm1">
<input type="text" /><br/>
<input type="text" /><br/>
<select>
<option>選項一</option>
<option>選項二</option>
</select>
<br/>
<input id="btn" type="button" value="提交" />
</form>
</body>
注意點
①$(":input")表示表單內所有的控制項,區別於$("input")只拿到input標籤,拿不到select等。
②index函數是jQuery中很有用的一個函數。
但實際情況中我們並不一定要迴圈獲得焦點,當提交按鈕獲得焦點的時候,我們就提交表單。
$(function(){
$(":input").keyup(function(e) {
var key = e.which;
if (13 == key) {
var index = $(":input").index(this);
var newIndex = index + 1;
$(":input:eq(" + newIndex + ")").focus();
}
});
$("#btn").click(function(){
$("frm1").submit();
});
});
摘自 IT胖子的專欄