跨Div输入框自动聚焦需求:满4位跳转,清空返回上一输入框
解决邮政编码输入框的自动跳转问题
我来帮你搞定这个输入框自动跳转的需求~你的原有代码失效主要有两个原因:一是两个输入框分别在不同的<div>里,next('.postcode input')无法跨父元素找到下一个输入框;二是没有处理Shift+Tab的默认跳转逻辑,导致出现异常。
先确认你的HTML结构(和你给出的一致):
<div class="postcode"> <div> <input type="text" maxlength="4"> </div> <div> <input type="text" maxlength="4"> </div> </div>
下面是修正后的jQuery代码,完美实现你要的功能:
$(".postcode input").on('keyup', function(e) { // 保留Shift+Tab的默认向前跳转行为,不做拦截 if (e.key === 'Tab' && e.shiftKey) { return; } const $currentInput = $(this); const maxLength = parseInt($currentInput.attr('maxlength'), 10); // 输入满指定长度时,自动聚焦到下一个输入框 if ($currentInput.val().length === maxLength) { const $nextInput = $currentInput.parent().next().find('input'); if ($nextInput.length) { $nextInput.focus(); } } // 按下退格键且当前输入框为空时,自动回到上一个输入框 if ($currentInput.val().length === 0 && e.key === 'Backspace') { const $prevInput = $currentInput.parent().prev().find('input'); if ($prevInput.length) { $prevInput.focus(); } } });
代码解释:
- 跨父元素查找输入框:不再直接用
next()找同级元素,而是先通过parent()找到当前输入框的父<div>,再用next()获取下一个<div>,最后find('input')拿到目标输入框,这样就解决了输入框不在同一父元素的问题。 - 保留Shift+Tab行为:判断到是Shift+Tab组合键时直接返回,让浏览器执行默认的向前跳转逻辑,避免异常。
- 退格回跳逻辑:当按下Backspace且当前输入框为空时,反向查找上一个父
<div>里的输入框并聚焦,满足删除第二个输入框内容后回到第一个的需求。 - 容错判断:加入
$nextInput.length和$prevInput.length的判断,避免没有下一个/上一个输入框时出现报错,即使后续扩展多个输入框也能兼容。
内容的提问来源于stack exchange,提问作者Ruben Kretek
相关产品推荐
相关产品推荐

