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

如何在事件监听器中传递待办项ID以更新待办列表条目内容

实现待办条目编辑更新功能的修改步骤

1. 修改条目渲染逻辑(renderTodos函数)

把原来的纯文本内容替换为可编辑的span元素,方便用户点击修改,同时顺便修复原代码选中状态无法持久化的问题:

function renderTodos(todos) {
  // clear list
  todoItemsList.innerHTML = '';
  // run through each item inside todos
  todos.forEach((item) => {
    // checkbox
    let cb = document.createElement('input');
    cb.type = 'checkbox';
    cb.classList.add('checkbox');
    cb.checked = item.completed; // 回显历史选中状态
    // 新增可编辑文本容器
    const textSpan = document.createElement('span');
    textSpan.classList.add('todo-text');
    textSpan.textContent = item.name;
    textSpan.contentEditable = true; // 开启编辑权限
    // delete button
    const deleteButton = document.createElement('button');
    deleteButton.className = 'delete-button';
    deleteButton.innerText = 'x';
    // lists
    const li = document.createElement('li');
    li.classList.add('item');
    if (item.completed) li.classList.add('checked'); // 回显已完成样式
    li.setAttribute('data-key', item.id);
    li.appendChild(cb);
    li.appendChild(textSpan); // 替换原有li.append(item.name)逻辑
    li.append(deleteButton);
    todoItemsList.append(li);
  });
}

2. 添加编辑事件监听和更新函数

在现有事件监听代码后新增以下内容:

// 监听文本编辑失焦事件,触发保存逻辑
todoItemsList.addEventListener('focusout', (e) => {
  if (e.target.classList.contains('todo-text')) {
    const todoId = Number(e.target.closest('li').dataset.key);
    const newText = e.target.textContent.trim();
    if (newText) { // 禁止将待办修改为空内容
      updateTodo(todoId, newText);
    } else {
      // 若用户清空了内容,自动恢复为原文本
      const originalTodo = todos.find(item => item.id === todoId);
      e.target.textContent = originalTodo.name;
    }
  }
});

// 体验优化:编辑时按回车键直接完成保存,避免产生换行
todoItemsList.addEventListener('keydown', (e) => {
  if (e.target.classList.contains('todo-text') && e.key === 'Enter') {
    e.preventDefault();
    e.target.blur();
  }
});

// 待办更新函数:同步修改内存数组和localStorage
function updateTodo(id, newName) {
  todos = todos.map(item => {
    if (item.id === id) {
      return {...item, name: newName};
    }
    return item;
  });
  addToLocalStorage(todos);
}

3. 可选优化:新增编辑状态样式(CSS部分追加)

让用户更清晰感知当前处于编辑状态:

.todo-text {
  padding: 2px 0;
}
.todo-text:focus {
  outline: none;
  border-bottom: 2px solid hsl(194, 100%, 70%);
}

额外兼容修复

原代码的复选框点击仅修改了样式,未同步到localStorage,可同步修改现有复选框点击逻辑:

document.addEventListener('click', (e) => {
  if (e.target.classList.contains('checkbox')) {
    const todoId = Number(e.target.closest('li').dataset.key);
    todos = todos.map(item => {
      if (item.id === todoId) {
        return {...item, completed: e.target.checked};
      }
      return item;
    });
    addToLocalStorage(todos);
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 09:00:05