【问题标题】:Setting the focus to the next input in jQuery?将焦点设置到jQuery中的下一个输入?
【发布时间】:2010-11-16 23:19:01
【问题描述】:

我目前有一个脚本,它会检查选择框的值,然后启用它旁边的文本字段,然后希望设置焦点。

我现在有这个在启用输入字段时效果很好......

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true);  }
    else { $(this).next('input').removeAttr("disabled"); }

});

说实话,我有点卡在“焦点”上,我试过“$(this).next('input').focus();”但这根本没有重点,尽管它也没有引发 Javascript 错误...

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); $(this).next('input').focus(); }
    else { $(this).next('input').removeAttr("disabled"); }

});

大家有什么想法吗?我真的坚持这一点,这对我正在构建的页面来说是一个非常简单但非常有用的补充!

谢谢

【问题讨论】:

  • 您也可以发布您的 HTML 吗?

标签: jquery focus next


【解决方案1】:

我认为您的问题可能是无法将焦点设置为禁用的输入控件(至少在某些浏览器/操作系统中)。

您的 focus() 调用基本上位于错误的块中 - 它应该在 else 块中,而不是 if 块中。

像这样:

$("#assessed select").change(function () {

    if($(this).val() == 'null') { $(this).next('input').attr("disabled", true); }
    else { $(this).next('input').removeAttr("disabled"); $(this).next('input').focus(); }
});

【讨论】:

  • 哈!非常感谢 Rob……我刚刚意识到我把重点放在“如果”而不是“其他”上!绝对的男生错误,对不起,非常感谢 - 直到你发布我才意识到:)
  • 记得缓存 $(this) 而不是多次调用它
【解决方案2】:

用缓存的这个 jq 对象修改了上面的答案。也不需要next里面的过滤器。 next() 只会返回下一个兄弟。过滤器基本上是说只有当它是输入或您提供的任何过滤器时才让我下一个。如果您确定下一个是所需的对象,则无需包含过滤器。

$("#assessed select").change(function () {
    var $this = $(this);
    if( $this.val() === 'null') {
        $this.next()
             .attr("disabled", true);
    }
    else {
        $this.next()
             .removeAttr("disabled")
             .focus();
    }
});

【讨论】:

  • 绝对完美,比我使用的解决方案更好,谢谢!
【解决方案3】:

还找到了一个不错的小插件来获取下一个输入:http://jqueryminute.com/set-focus-to-the-next-input-field-with-jquery/

$.fn.focusNextInputField = function() {
    return this.each(function() {
        var fields = $(this).parents('form:eq(0),body').find('button,input,textarea,select').not(':hidden');
        var index = fields.index( this );
        if ( index > -1 && ( index + 1 ) < fields.length ) {
            fields.eq( index + 1 ).focus();
        }
        else {fields.first().focus();}
        return false;
    });
};

【讨论】:

  • 我会在字段声明中添加.not(':hidden'),因此只选择可见元素。另外,添加else {fields.first().focus();} 以使焦点环绕到第一个元素。
  • 为什么要先找parents form:eq(0)?
  • @Serge 它选择输入元素所在的父表单。我不知道“eq(0)”是否必要,不是我的代码,所以我不确定。跨度>
  • 好主意@CollinK - 我已将其添加到
  • 我还会在字段声明中添加一个.not(':disabled'),因此只选择未禁用的元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-01-28
  • 2017-01-09
相关资源
最近更新 更多