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

jQuery多输入框自动跳转与粘贴分配功能,keyup跳转到下一个输入框失效如何修复?

问题原因

原代码存在3处核心错误:

  1. 退格逻辑的DOM遍历路径错误:$(this).prev()是找当前元素的同级节点,但输入框外层嵌套了form-group和col层,无法正确定位上一个输入框
  2. 事件绑定范围错误:keyup事件直接绑定在.col容器上,没有委托给内部的.press输入框,退格逻辑的触发上下文错误
  3. 未实现粘贴自动分配内容的逻辑

修正后的完整实现

JS代码

// 事件绑定支持静态/动态生成的输入框
$(document).on('input', '.press', function() {
    // 需求1:输入满maxLength自动跳转到下一个输入框
    const maxLen = parseInt(this.maxLength);
    if (this.value.length >= maxLen) {
        const $nextCol = $(this).closest('.col').next('.col');
        if ($nextCol.length) {
            $nextCol.find('input.press').focus();
        }
    }
}).on('keyup', '.press', function(e) {
    // 需求2:退格且当前输入框为空时跳转到上一个输入框
    if (e.which === 8 && !this.value.trim()) {
        const $prevCol = $(this).closest('.col').prev('.col');
        if ($prevCol.length) {
            const $prevInput = $prevCol.find('input.press');
            $prevInput.focus();
            // 跳转后自动清空上个输入框内容,方便直接替换
            $prevInput.val('');
        }
    }
}).on('paste', '.press', function(e) {
    // 需求3:粘贴内容自动按maxLength分配到所有输入框
    e.preventDefault();
    const pasteText = (e.originalEvent.clipboardData || window.clipboardData).getData('text').trim();
    const $allInputs = $('.press');
    let currentIndex = $(this).index('.press');
    let remainingText = pasteText;

    $allInputs.slice(currentIndex).each(function() {
        if (remainingText.length <= 0) return false;
        const maxLen = parseInt(this.maxLength);
        const chunk = remainingText.slice(0, maxLen);
        this.value = chunk;
        remainingText = remainingText.slice(maxLen);
    });

    // 粘贴完成后定位到最后一个有内容的输入框
    const lastFilledIndex = Math.min(currentIndex + pasteText.length, $allInputs.length - 1);
    $allInputs.eq(lastFilledIndex).focus();
});

CSS代码(可直接复用原代码)

body{display: flex;}
.form-control{width: 70px;
margin-right: 10px;}

HTML代码(可直接复用原代码)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div class="form-group">
<input type="text" class="press form-control" name="code" maxlength="1" autocomplete="off">
</div>
</div>

<div class="col">
<div class="form-group">
<input type="text" class="press form-control"  name="code" maxlength="1" autocomplete="off">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="press form-control"  name="code" maxlength="1" autocomplete="off">
</div>
</div>
<div class="col">
<div class="form-group">
<input type="text" class="press form-control"  name="code" maxlength="1" autocomplete="off">
</div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 03:54:02