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

多Div父节点事件监听下表格删除确认弹窗无法关闭问题求解

问题根因

你触发closeDeleteWindow函数时的事件绑定对象是.buttonNo按钮,e.currentTarget指向的就是当前被点击的No按钮本身,而.confirmWindow是No按钮的父级容器,你在子元素内部调用querySelector找父级元素当然找不到,代码执行报错后自然没法让弹窗消失。

修复方案

直接替换你的JS代码为以下版本即可,同时补充了Yes按钮的用户行删除逻辑:

const deleteButton = document.querySelectorAll('.trashIcon');
const buttonYes = document.querySelectorAll('.buttonYes');
const buttonNo = document.querySelectorAll('.buttonNo');

function openWindow() {
  this.parentNode.querySelector('.confirmWindow').classList.remove('hidden');
  this.classList.add('hidden');
}

function closeDeleteWindow() {
  // 先找到当前按钮所属的confirmWindow容器
  const confirmWindow = this.closest('.confirmWindow');
  confirmWindow.classList.add('hidden');
  // 把隐藏的删除图标重新显示出来
  confirmWindow.parentNode.querySelector('.trashIcon').classList.remove('hidden');
}

function deleteUserRow() {
  // 找到当前行的tr元素直接移除
  const currentRow = this.closest('.table-row');
  currentRow.remove();
}

for (let i=0; i < deleteButton.length; i++){
  deleteButton[i].addEventListener('click', openWindow);
}

for (let i=0; i < buttonNo.length; i++){
  buttonNo[i].addEventListener('click', closeDeleteWindow);
}

// 给Yes按钮绑定删除事件
for (let i=0; i < buttonYes.length; i++){
  buttonYes[i].addEventListener('click', deleteUserRow);
}

逻辑说明

  • 用closest()方法向上查找匹配的祖先元素,避免层级嵌套变化导致的选择器失效问题,比parentNode兼容性和稳定性更好
  • 关闭弹窗时同时恢复删除按钮的显示,符合常规交互逻辑
  • 新增的删除逻辑直接定位到当前用户所在的表格行,调用remove()方法即可完成删除操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 17:06:01