閱讀317 返回首頁    go 阿裏雲 go 技術社區[雲棲]


jQuery控製回車使表單內控件獲得焦點

 
<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 >
           <input type="text" /><br/>
    <input type="text" /><br/>
    <select>
       <option>選項一</option>
       <option>選項二</option>
    </select>
    <br/>
    <input 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();
   });

});

 

 

最後更新:2017-04-02 18:14:51

  上一篇:go 【Android MyEclipse】no projects are found to import 如何解決
  下一篇:go C++實現判斷輸入的數組是否是升序的程序