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

如何用JS点击表格外独立按钮删除当前聚焦输入框所属的表格行

实现方案

核心逻辑是提前记录用户最后聚焦的输入框所在的行,解决点击外部按钮时输入框失焦无法直接获取的问题。

基础实现(适用于固定行的表格)

给所有表格内的输入框绑定聚焦事件,记录当前激活的行,点击移除按钮时删除该行:

// 存储当前选中的表格行
let activeTableRow = null;

// 绑定所有输入框的聚焦事件
document.querySelectorAll('#ListTab .UiListRow input').forEach(input => {
  input.addEventListener('focus', function() {
    activeTableRow = this.closest('tr.UiListRow');
  });
});

// 移除行函数
function removeRow() {
  if (!activeTableRow) return;
  activeTableRow.remove();
  activeTableRow = null;
}

优化实现(支持动态新增行的表格)

使用事件委托监听表格的focusin事件(支持冒泡,无需开启捕获),适配后续动态添加的表格行:

let activeTableRow = null;

// 事件委托,兼容动态新增的行
document.getElementById('ListTab').addEventListener('focusin', e => {
  const targetInput = e.target;
  if (targetInput.tagName === 'INPUT' && targetInput.closest('tr.UiListRow')) {
    activeTableRow = targetInput.closest('tr.UiListRow');
  }
});

function removeRow() {
  // 可选:删除后自动聚焦到上/下一行的输入框,优化操作体验
  if (activeTableRow?.nextElementSibling) {
    activeTableRow.nextElementSibling.querySelector('input').focus();
  } else if (activeTableRow?.previousElementSibling) {
    activeTableRow.previousElementSibling.querySelector('input').focus();
  }
  activeTableRow?.remove();
  activeTableRow = null;
}

注意事项

  • 不要直接在removeRow里用document.activeElement获取输入框,点击外部按钮时输入框会提前失焦,拿到的会是移除按钮元素
  • closest方法会向上遍历DOM查找最近的匹配元素,相比手动遍历父节点兼容性更好、逻辑更简洁
  • 若要适配老版本浏览器,可以把?.可选链语法换成普通的if判断即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:21:02