當輸入框較多時,一個一個寫keydown事件未免有些麻煩.
$.extend($.fn, {
/**
*
*輸入框切換焦點.方向鍵上、方向鍵下、回車鍵切換焦點,
*當傳入了$submit且焦點在最後一個輸入框時按回車鍵調用$submit的單擊事件.
*使用eg:
*1、$(".swicthInput").switchFocus($("#submit"));
*2、$("#userName,#password").switchFocus($("#submit"));
*
*/
switchFocus:function($submit){
var that=this;
that.keydown(function(e){
var code=e.keyCode;
if(code!="13"&&code!="40"&&code!="38"){
return;
}
var nextIndex=that.index(this);
code=="38"?nextIndex--:nextIndex++;
var next=that.get(nextIndex);
if(!next){
if($submit&&code=="13"){
$submit.click();
return;
}
next=code=="38"?that.last():that.first();
}
next.focus();
});
return this;
}
});