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

Blazor环境下6个输入框自动跳转失效,求排查问题

问题排查与修复方案

核心错误分析

你的代码没有效果主要存在两个关键问题:

  1. 索引参数传递错误:第一个输入框传入的nextIndex=1,但它本身就是父容器的nth-child(1),实际找的是自身,自然无法跳转到下一个输入框。正确逻辑应为:第一个输入框需定位nth-child(2),也就是传入nextIndex=2,以此类推,第五个输入框要传nextIndex=6。
  2. DOM结构依赖型选择器不稳定:在Blazor环境中,组件重渲染可能改变DOM结构,nth-child这种依赖位置的选择器容易失效,建议改用更可靠的元素关系或ID定位方式。

修复后的代码实现

方案1:优化原生JS逻辑(无需传递索引)

修改JS函数,直接通过元素关系获取下一个输入框,避免依赖索引参数,稳定性更强:

function focusNext(currentInput) {
  // 仅在输入有效非空字符时触发跳转
  if (currentInput.value.trim().length === 1) {
    const nextInput = currentInput.nextElementSibling;
    if (nextInput && nextInput.tagName === 'INPUT') {
      nextInput.focus();
    }
  }
}

对应的HTML部分统一调用即可:

<div class="code-input">
  <input type="text" @bind=code0 maxlength="1" onkeyup="focusNext(this)">
  <input type="text" @bind=code1 maxlength="1" onkeyup="focusNext(this)">
  <input type="text" @bind=code2 maxlength="1" onkeyup="focusNext(this)">
  <input type="text" @bind=code3 maxlength="1" onkeyup="focusNext(this)">
  <input type="text" @bind=code4 maxlength="1" onkeyup="focusNext(this)">
  <input type="text" @bind=code5 maxlength="1">
</div>

方案2:使用Blazor原生事件(更贴合框架习惯)

如果不想依赖原生JS,完全可以用Blazor的C#事件处理,规避JS交互的潜在冲突:

  1. 组件代码中定义字段与处理方法:
private string code0, code1, code2, code3, code4, code5;
private ElementReference[] inputRefs = new ElementReference[6];

private async Task OnInputChanged(int currentIndex)
{
    if (currentIndex < 5)
    {
        await inputRefs[currentIndex + 1].FocusAsync();
    }
}
  1. 对应的HTML绑定:
<div class="code-input">
  <input type="text" @bind=code0 maxlength="1" @ref="inputRefs[0]" @oninput="() => OnInputChanged(0)">
  <input type="text" @bind=code1 maxlength="1" @ref="inputRefs[1]" @oninput="() => OnInputChanged(1)">
  <input type="text" @bind=code2 maxlength="1" @ref="inputRefs[2]" @oninput="() => OnInputChanged(2)">
  <input type="text" @bind=code3 maxlength="1" @ref="inputRefs[3]" @oninput="() => OnInputChanged(3)">
  <input type="text" @bind=code4 maxlength="1" @ref="inputRefs[4]" @oninput="() => OnInputChanged(4)">
  <input type="text" @bind=code5 maxlength="1" @ref="inputRefs[5]">
</div>

额外优化建议

  • 增加删除键回退逻辑:当用户按删除键清空当前输入框时,自动聚焦到上一个输入框,提升操作体验
  • 限制输入字符类型:可在输入事件中过滤非法字符,确保仅接收数字或指定类型的输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 13:52:25