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

如何在JavaScript中编辑其他列表项行?

问题解决:新增Todo项的编辑功能实现

问题根源

你遇到的问题核心是:

  • 初始代码用document.querySelector仅获取了页面中第一个匹配的.item_name和.item_edit元素,新增的列表项根本没绑定编辑事件。
  • 共用全局的newItemInput会导致所有编辑操作混乱,无法对应到单个项。

解决方案

改用事件委托绑定点击逻辑,同时为每个编辑项单独处理输入框,确保操作对应到当前列表项:

1. 修复createItem函数的语法错误

先修正按钮的语法错误(多了个多余的}):

// createItem
function createItem(text, id) {
  const itemRow = document.createElement('li');
  itemRow.setAttribute('class', 'item_row');
  itemRow.setAttribute('data-id', id || Date.now());
  itemRow.innerHTML = `
    <div class="item">
        <button class="list__done" >
          <i class="fa-sharp fa-regular fa-circle-check"></i>
        </button>
        <span class="item_name">${text}</span>

      <div class="button_container">
            <button class="item_edit">Edit</button>
            <button class="item_delete" >
                <i class="fas fa-trash-alt" data-id=${id || Date.now()}></i>
            </button>
      </div>
    </div>
    <div class="item_divider"></div>`;
  return itemRow;
}

2. 替换编辑逻辑为事件委托

移除原来的全局元素获取和单个按钮绑定,改成监听父容器的点击事件:

// 事件委托:绑定到.items容器,监听所有编辑按钮点击
document.querySelector('.items').addEventListener('click', (event) => {
  // 只处理编辑按钮的点击
  if (!event.target.classList.contains('item_edit')) return;

  const editBtn = event.target;
  // 定位当前项的文本节点
  const itemName = editBtn.closest('.item').querySelector('.item_name');

  if (editBtn.innerText === 'Update') {
    // 获取当前项的输入框,更新文本
    const input = itemName.querySelector('.newItemInput');
    itemName.innerText = input.value.trim();
    editBtn.innerText = 'Edit';
    saveItems(); // 保存更新后的数据
  } else {
    // 为当前项创建独立的输入框
    const newItemInput = document.createElement('input');
    newItemInput.type = 'text';
    newItemInput.className = 'newItemInput';
    newItemInput.value = itemName.innerText;
    
    itemName.innerHTML = '';
    itemName.appendChild(newItemInput);
    newItemInput.focus();
    editBtn.innerText = 'Update';
  }
});

// 确保saveItems能正确收集所有项数据
function saveItems() {
  const items = document.querySelectorAll('.item_row');
  const todoItems = Array.from(items).map(item => ({
    id: item.dataset.id,
    text: item.querySelector('.item_name').innerText
  }));
  localStorage.setItem('todos', JSON.stringify(todoItems));
}

关键说明

  • 事件委托:利用DOM事件冒泡机制,父容器.items监听所有子元素的点击,不管是初始项还是新增项,都能触发编辑逻辑。
  • 独立输入框:每次编辑时为当前项创建新的输入框,避免全局共用导致的操作混乱。
  • 节点定位:用closest('.item')快速找到当前项的容器,精准定位对应的文本节点。

内容的提问来源于stack exchange,提问作者Chocolate covered Strawberry

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 17:32:51