使用jQuery选择焦点上的文本框在移动浏览器中不起作用

时间:2012-07-31 13:32:46

标签: javascript jquery html

我在一个页面上有四个文本框,其中包含maxlength 4.我的目标是当用户填充第一个文本框时,焦点会自动移动到另一个文本框。我编写的方法适用于所有Web浏览器,但不适用于移动浏览器。

我正在使用的标记:

<input tabindex="3" type="text" id="cnumber1" class="inputBx ccNumber" style="width:57px;margin-left: 11px!important" maxlength="4" size="4" autocomplete="off" />
        <input tabindex="4" type="text" id="cnumber2" class="ccNumber" style="width:57px;"  maxlength="4" size="4" autocomplete="off"/>
        <input tabindex="5" type="text" id="cnumber3" class="ccNumber" style="width:56px;"  maxlength="4" size="4" autocomplete="off"/>
        <input tabindex="6" type="text" id="cnumber4" class="ccNumber" style="width:56px;"  maxlength="4" size="4" autocomplete="off"/>

我正在使用的Jquery方法:

(function($) {
  $.switchFocus = function($this) {
    $this.unbind('keyup');
    $this.each(function() {
      $(this).keyup(function(){
        var $this = $(this),
        inputVal = $this.val(),
        iLen = inputVal.length,
        $nextEle = $this.next();
        if (iLen == $this.attr("size") && $nextEle.length > 0){
          if($nextEle.val().length === 0)
            $nextEle.focus();
        }
      });
    });
  }
}(jQuery));

我可以请一些帮助,了解移动浏览器出现这种情况的原因吗?

1 个答案:

答案 0 :(得分:0)

对于某些移动浏览器来说,它必定是一个错误,但这种方法可以解决您的问题,尝试一下,

(function($) {
  $.switchFocus = function($this) {
    $this.unbind('keyup');
    $this.each(function() {
      $(this).keyup(function(){
        var $this = $(this),
        inputVal = $this.val(),
        iLen = inputVal.length,
        $nextEle = $this.next();
        if (iLen == $this.attr("size") && $nextEle.length > 0){
          if($nextEle.val().length === 0)
            $nextEle.focus();
            setTimeout(function(){$nextEle.focus()},0);
        }
      });
    });
  }
}(jQuery));

DEMO