jQuery控制回车使表单内控件得到焦点

<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript">
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();
       }
   });
});
java

</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>
jquery

 

注意点函数

①$(":input")表示表单内全部的控件,区别于$("input")只拿到input标签,拿不到select等。
②index函数是jQuery中颇有用的一个函数。
this


但实际状况中咱们并不必定要循环得到焦点,当提交按钮得到焦点的时候,咱们就提交表单。spa

$(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();
      }
   });
orm

   $("#btn").click(function(){
       $("frm1").submit();
   });
ip

});input

相关文章
相关标签/搜索