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

来源:互联网 发布:卫星电视 网络电视 编辑:程序博客网 时间:2024/06/16 00:08

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

});

 

 

原创粉丝点击