0

我有一个表单,我可以通过serializeArray(). 我想focus()使用 enter 键根据它们的 tabindex 值来处理表单元素。只有当它具有价值或专注于自身时。

对 jQuery 来说没什么新意,所以如果有任何错误......

$.fn.entertab = function()
  {

 var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
  var maxTabIndex = 20;
        var elements = this.serializeArray();
     $.each(elements, function(i, element)
        {

 this.keypress(function(e){ 
    var nTabIndex=this.tabIndex;
       var myNode=this.nodeName.toLowerCase();
            if(nTabIndex > 0 && key == 13 && nTabIndex <= maxTabIndex && ((!myNode.attr("disabled")) || (myNode.val == "")))
      {
   myNode.focus(); 
   }
   else
   {
   nTabIndex=this.tabIndex+1;
      myNode.focus();
   }
   });

     });
        }
  $("theform").entertab();
4

2 回答 2

1

你也可以试试这个 HTML

<input id="122" class='TabOnEnter' tabindex="1" /><br>
<input id="123" class='TabOnEnter' tabindex="2" /><br>
<input id="124" class='TabOnEnter' tabindex="4" />This input is hidden<br>
<input id="124" class='TabOnEnter' tabindex="5" /><br>
<input id="125" class='TabOnEnter' tabindex="3" /><br>
<textarea class='TabOnEnter' tabindex="6">Hi, I am a test area</textarea>

脚本 ///////////

$(document).on("keypress", ".TabOnEnter" , function(e)
  {
    //Only do something when the user presses enter
    if( e.keyCode ==  13 )
    {
       var nextElement = $('[tabindex="' + (this.tabIndex+1)  + '"]');
       console.log( this , nextElement ); 
       if(nextElement.length )
         nextElement.focus()
       else
         $('[tabindex="1"]').focus();  
    }   
  });

//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut();  })

///////////// 在 EI、Chrome、Mozilla 中运行良好。未在 safari 和其他浏览器中测试

于 2013-07-31T13:04:20.353 回答
0

我想我明白你想做什么。我重写了你的代码,结果是这样的:

(function($){

    $.fn.entertab = function(options) {

        var defaults = {
            maxTabIndex: 20
        };

        options = $.extend({}, defaults, options);

        return this.filter('form').each(function(){

            var $this = $(this),
                $elms = $this.find("[tabindex]");

            $elms.each(function(){
                var $elm = $(this),
                    idx = parseInt($elm.attr("tabindex"));
                if (idx > options.maxTabIndex) {
                    return;
                }
                $elm.keydown(function(e){
                    if (e.which == 13 && ($elm.val() != '')) {
                        $elms.filter("[tabindex="+(idx+1)+"]").focus();
                        e.preventDefault();
                    }
                });
            });
        });
    };

})(jQuery);

jsFiddle上有一个工作示例。

于 2011-01-08T12:05:30.507 回答