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

jQuery输入框达maxlength后自动跳转功能失效问题排查

问题分析与解决方案

1. 事件绑定失效的核心原因

你的jQuery代码未生效,主要是因为代码执行时机早于DOM元素加载完成。如果脚本放在<head>标签或HTML结构之前,此时.inputs选择器还无法找到对应的输入框,自然无法完成事件绑定。

修复方式

将jQuery代码包裹在$(document).ready()回调中,确保DOM加载完成后再执行事件绑定:

$(document).ready(function() {
  $(".inputs").keyup(function () {
    if (this.value.length == this.maxLength) {
      // 修正下一个输入框的定位逻辑
      const nextInput = $(this).parent('.empty_status').next('.empty_status').find('.inputs');
      if (nextInput.length) {
        nextInput.focus();
      }
    }
  });
});

或者直接将脚本标签放在HTML结构的末尾(</body>标签之前),也能保证DOM元素已存在。

2. 下一个输入框定位错误

原代码中$(this).next('.inputs')无法找到目标输入框,因为每个.inputs元素都被包裹在独立的.empty_status容器中,它们并不是直接的兄弟节点。

修正逻辑

需要先向上遍历到父容器.empty_status,再找到下一个同级的.empty_status,最后在其中查找.inputs元素:

$(this).parent('.empty_status').next('.empty_status').find('.inputs')

同时增加if (nextInput.length)判断,避免最后一个输入框尝试聚焦不存在的元素。

额外优化建议

可以添加退格键跳转上一个输入框的逻辑,提升用户体验:

$(document).ready(function() {
  $(".inputs").keyup(function (e) {
    if (this.value.length == this.maxLength) {
      const nextInput = $(this).parent('.empty_status').next('.empty_status').find('.inputs');
      if (nextInput.length) {
        nextInput.focus();
      }
    } else if (e.key === 'Backspace' && this.value.length === 0) {
      const prevInput = $(this).parent('.empty_status').prev('.empty_status').find('.inputs');
      if (prevInput.length) {
        prevInput.focus();
      }
    }
  });
});

内容的提问来源于stack exchange,提问作者Mike Ledford

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:28:20