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

JS map函数中li、span元素调用append方法未按预期生效问题

问题原因与修复方案

问题根源

  • 核心错误:Element.append()方法仅执行节点插入操作,无返回值(固定返回undefined)。原代码中let newEl = newLi.append(newSpan) 给newEl赋值为undefined,map遍历最终返回的数组全是undefined,并非组装好的li元素。
  • 逻辑瑕疵:每次提交新待办时都会遍历全量todos数组生成所有条目,直接append到列表会导致旧条目重复渲染。

修复方案

调整map内逻辑,执行append插入操作后直接返回li元素本身,同时在渲染前清空列表避免重复内容:

const addTodoForm = document.querySelector(`[name="todo--form"]`);
const todoList = document.querySelector('.todo--list');
const todos = [];

function handleSubmit(e) {
  e.preventDefault();
  const text = this.querySelector(`[name="todo--input"]`).value;
  const item = {
    text: text,
    finished: false,
  };

  if (text) {
    todos.push(item);
    addTodoForm.reset();
    // 清空现有列表,避免重复渲染旧条目
    todoList.innerHTML = '';
    const todoItems = todos.map((todo) => {
      const newSpan = document.createElement('span');
      const newLi = document.createElement('li');
      newSpan.textContent = todo.text;
      newLi.append(newSpan);
      // 直接返回组装完成的li元素,不要返回append的执行结果
      return newLi;
    });
    todoList.append(...todoItems);
  }
}

addTodoForm.addEventListener('submit', handleSubmit);

如果追求更好的性能,也可以省略全量数组遍历,每次提交时仅创建新待办对应的单个li元素,直接插入列表即可,不需要重绘所有已有条目。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 05:48:28