使用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
相关产品推荐
相关产品推荐

