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

使用JS Class开发Todo List时无法添加待办项的问题求助

Todo List添加功能错误修复方案

存在的问题

  • HTML部分onClick绑定错误:TodoAddCommand是类,不是可直接执行的函数,点击事件触发时不会自动实例化类并执行方法
  • 拼写错误1:获取数组长度时写的Todos.lenght,正确拼写为Todos.length
  • 拼写错误2:打印语句写的console.logo,正确拼写为console.log
  • 取值逻辑错误:this.event.data无法获取输入框的内容,点击事件对象没有data属性,需要主动获取输入框DOM的value属性
  • 类的使用逻辑错误:仅定义了类但没有实例化、调用execute方法的触发逻辑

修复后的代码

HTML代码

<input type="text" id="addTodo" />
<button onClick="handleAddTodo()">
Add
</button>

JS代码

let Todos = [
  {
    id: 0,
    content: "test",
    done: false
  }
]

class TodoAddCommand {
  constructor(inputValue) {
    this.content = inputValue;
  }
  
  execute() {
    const todo = {
      id: Todos.length,
      content: this.content,
      done: false,
    }
    Todos.push(todo);
    console.log(Todos);
  }
}

// 点击事件处理函数
function handleAddTodo() {
  const inputEl = document.getElementById('addTodo');
  const inputValue = inputEl.value.trim();
  // 空内容不执行添加
  if (!inputValue) return;
  const addCommand = new TodoAddCommand(inputValue);
  addCommand.execute();
  // 添加完成后清空输入框
  inputEl.value = '';
}

关键修改说明

  • 新增handleAddTodo作为点击事件的触发函数,负责获取输入框内容、实例化TodoAddCommand类并调用execute方法
  • 修正所有拼写错误
  • 调整类的入参逻辑,直接传入输入框内容,避免错误的事件属性取值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 00:45:05