首页 > 解决方案 > 使用类的待办事项列表

问题描述

所以我正在学习 JS 课程,我一开始就面临一个问题,我无法在我的列表中添加任何待办事项。我找不到解决方案我做错了什么。我的代码:

<input type="text" id="addTodo" />
<button onClick="TodoAddCommand">
Add
</button>

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

]
class TodoAddCommand {
    constructor(e) {
  this.event = e;
  }
  
  execute() {
  const todo = {
    id: Todos.lenght,
    content: this.event.data,
    done: false,
  }
  
  Todos.push(todo);
  console.logo(Todos);
  }
}

标签: javascript

解决方案


TodoAddCommand是一个类;你试图把它当作一个函数来调用。

相反,创建一个新实例TodoAddCommand并将事件传递给构造函数,然后调用execute()

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

]
class TodoAddCommand {
  constructor(e) {
    this.event = e;
  }

  execute() {
    const todo = {
      id: Todos.lenght,
      content: this.event.data,
      done: false,
    }

    Todos.push(todo);
    console.log(Todos);
  }
}
<input type="text" id="addTodo" />
<button onClick="new TodoAddCommand(event).execute()">
Add
</button>


推荐阅读