版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xinshijimanon/article/details/62045706
当输入框较多时,一个一个写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;
}
});