You need to enable JavaScript to run this app. JavaScript开发杂货清单应用时为每个li添加删除按钮失效怎么解决
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript开发杂货清单应用时为每个li添加删除按钮失效怎么解决

问题原因

你的代码问题出在displayGroceries函数的逻辑顺序上:

  • 创建删除按钮的代码写在了for循环外面,只会在循环结束后给最后一个li加按钮,还会出现循环变量i的作用域异常问题
  • 你获取到的按钮id是字符串类型,直接传给splice会有隐式类型转换的潜在风险
  • 循环内每次创建li之后,没有同步给当前li生成对应的删除按钮
修复后的完整代码

JS 代码

let addButton = document.getElementById('add-button');
addButton.addEventListener('click', add);

let addInput = document.getElementById('add-input');

let groceryList = []

function add() {
  // 新增变量声明+空值校验,避免全局污染和空项添加
  let groceryInput = addInput.value;
  if(groceryInput.trim() === '') return
  groceryList.push(groceryInput);
  addInput.value = '';
  displayGroceries();
}

function remove(event) {
  // 把id转成数字类型再调用splice
  let position = Number(event.currentTarget.id);
  groceryList.splice(position, 1);
  displayGroceries();
}

function displayGroceries() {
  let groceryUl = document.getElementById('grocery-ul');
  groceryUl.innerHTML = '';

  for (let i = 0; i < groceryList.length; i++) {
    let groceryLi = document.createElement('li');
    groceryLi.innerHTML = groceryList[i];
    groceryUl.appendChild(groceryLi);

    // 删除按钮生成逻辑移到for循环内部,每个li对应生成一个按钮
    let removeButton = document.createElement('button');
    removeButton.innerText = "Remove";
    removeButton.addEventListener('click', remove);
    removeButton.id = i;
    groceryLi.appendChild(removeButton);
  }
}

HTML 代码(无需改动)

<div class="container">
  <h1>Grocery List</h1>
  <input id="add-input" placeholder="Add Groceries" autocomplete="off">
  <button id="add-button">Add</button>
  <div>
    <ul id="grocery-ul"></ul>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 14:24:02