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

Vanilla JS预算应用:动态渲染收支项的删除功能故障排查

解决方案

1. 修复动态元素的事件绑定问题

由于你的<li>和删除按钮是动态生成的,直接给按钮绑定addEventListener会失效,必须通过事件委托绑定到静态父元素(比如承载列表的<ul>)上:

// 假设你的列表容器ul的id是"budget-list"
document.getElementById('budget-list').addEventListener('click', function(e) {
  // 判断点击的是删除按钮
  if (e.target.classList.contains('delete-btn')) {
    const entryId = parseInt(e.target.dataset.entryId);
    handleDelete(entryId);
  }
});

2. 修正数组元素的删除逻辑

不要盲目使用splice,先通过唯一ID找到数组中对应元素的索引,再执行删除:

function handleDelete(entryId) {
  // 找到数组中匹配ID的元素索引
  const targetIndex = entry_list.findIndex(item => item.id === entryId);
  if (targetIndex !== -1) {
    // 从数组移除对应元素
    entry_list.splice(targetIndex, 1);
    // 从DOM移除对应的<li>
    document.getElementById(`entry-${entryId}`).remove();
  }
}

3. 优化动态渲染时的ID绑定

生成<li>和按钮时,用data-*属性存储ID(比直接用元素id更灵活),同时确保ID类型统一(Date.now()生成的是数字,避免和字符串混淆):

function renderEntry(entry) {
  const li = document.createElement('li');
  li.id = `entry-${entry.id}`; // 给<li>设置唯一标识ID
  
  const deleteBtn = document.createElement('button');
  deleteBtn.classList.add('delete-btn');
  deleteBtn.textContent = '删除';
  deleteBtn.dataset.entryId = entry.id; // 用data属性存储对应条目ID
  
  // 添加条目其他内容(比如金额、标签等)
  li.innerHTML += `<span>${entry.amount}元</span><span>${entry.tag}</span>`;
  li.appendChild(deleteBtn);
  
  document.getElementById('budget-list').appendChild(li);
}

常见排查点

  • 确认entry_list中的每个对象都正确包含id属性,且值为Date.now()生成的数字
  • 检查点击删除按钮时,获取到的ID和数组中存储的ID类型一致(比如都是数字,避免字符串和数字不匹配)
  • 若Date.now()存在极低概率的重复风险,可改为Date.now() + Math.floor(Math.random() * 1000)生成ID

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 17:01:17