You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改jQuery实现含label包裹的输入框自动跳转功能

核心实现思路

原来的.next()方法只能匹配同级兄弟元素,第一个输入框被<label>包裹后和其他输入框不在同一个层级,自然无法匹配到下一个输入框。我们可以提前收集表单内所有的目标输入框集合,通过索引定位下一个需要跳转的输入框,完全不受父容器结构的影响。

修改后的jQuery代码

// 提前收集表单内所有单字符输入框,顺序和页面显示顺序一致
const $allInputs = $('#jumble_word .inputs');

$allInputs.keyup(function() {
  // 获取当前输入框在集合中的索引
  const currentIndex = $allInputs.index(this);
  // 输入满最大长度时跳转到下一个输入框
  if (this.value.length === this.maxLength && currentIndex < $allInputs.length - 1) {
    $allInputs.eq(currentIndex + 1).focus();
  }
});

可选优化(退格回跳)

如果需要实现按退格键删除当前输入框内容后自动跳回上一个输入框,可以扩展代码如下:

const $allInputs = $('#jumble_word .inputs');

$allInputs.on('keyup', function(e) {
  const currentIndex = $allInputs.index(this);
  // 输入满长度后自动下跳
  if (this.value.length === this.maxLength && currentIndex < $allInputs.length - 1) {
    $allInputs.eq(currentIndex + 1).focus();
  }
  // 按退格键且当前输入框为空时自动回跳
  if (e.key === 'Backspace' && this.value.length === 0 && currentIndex > 0) {
    $allInputs.eq(currentIndex - 1).focus();
  }
});

以上实现无需修改现有HTML和CSS结构,不管后续有多少个输入框被label包裹都能正常生效。

内容的提问来源于stack exchange,提问作者Steven Erickson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 10:39:00