贝利信息

标题:如何在表单最后一个输入框按回车时动态添加一行新表单并自动聚焦

日期:2026-01-24 00:00 / 作者:聖光之護

本文详解如何通过现代 dom 事件监听实现“在表格最后一列输入框按下 enter 键时,仅新增一行结构相同的表单行,并将焦点自动移至新行首个输入框”,避免重复创建、焦点错位及旧式 `onkeypress` 嵌套调用导致的逻辑混乱。

传统方案(如原代码中为每个 绑定 onkeypress="return tabE(this,event)")存在严重缺陷:

✅ 正确解法应遵循 事件委托 + 精准条件判断 + 单次克隆 原则。以下是优化后的完整实现:

✅ 推荐方案:基于事件委托的优雅实现

  
1 2 3 4 5
const display = document.getElementById("area");
const tbody = document.getElementById("t1");

// 使用事件委托:监听 tbody,捕获所有 input 的 keypress
tbody.addEventListener("keypress", function (e) {
  // 仅响应 Enter 键(兼容性优于 keyCode)
  if (e.code !== "Enter") return;

  const target = e.target;
  // 确保触发源是 input,且带有 .last 类(标识最后一列)
  if (!target.matches("inp

ut.last")) { // 非最后一列:跳转到同一行的下一列 input const currentTd = target.closest("td"); const nextTd = currentTd.nextElementSibling; if (nextTd) { const nextInput = nextTd.querySelector("input"); if (nextInput) nextInput.focus(); } e.preventDefault(); // 阻止默认换行或提交行为 return; } // ✅ 是最后一列 → 克隆当前行,清空值,追加到 tbody,并聚焦首输入框 const newRow = tbody.querySelector("tr").cloneNode(true); newRow.querySelectorAll("input").forEach(inp => inp.value = ""); // 清空所有输入值 tbody.appendChild(newRow); // 聚焦新行第一个 input(确保可编辑) const firstInput = newRow.querySelector("input"); if (firstInput) firstInput.focus(); e.preventDefault(); // 关键:阻止表单默认提交或页面跳动 });

? 关键改进点说明: