使用JavaScript类构建待办事项列表,能够将任务相关的属性和操作封装在同一个类中,避免全局变量污染,也让功能逻辑更模块化。这种方式比零散的函数写法更利于代码的复用和后续功能迭代。

定义待办事项类的基础结构
首先我们需要创建一个TodoList类,这个类需要包含存储所有任务的属性,以及操作任务的相关方法。任务本身也可以用一个简单的类来封装,包含任务内容、完成状态等属性。
// 单个待办任务类
class TodoItem {
constructor(content) {
this.content = content; // 任务内容
this.id = Date.now() + Math.random().toString(36).slice(2); // 唯一标识
this.isCompleted = false; // 完成状态,默认未完成
}
// 切换完成状态
toggleStatus() {
this.isCompleted = !this.isCompleted;
}
}
// 待办事项列表管理类
class TodoList {
constructor() {
this.todoList = []; // 存储所有待办任务
}
}
实现核心功能方法
接下来给TodoList类添加添加任务、删除任务、获取任务列表等核心方法,所有操作都围绕内部的todoList数组展开。
添加任务方法
添加任务时,先创建TodoItem实例,再将其推入任务数组即可。
class TodoList {
constructor() {
this.todoList = [];
}
// 添加新任务
addTodo(content) {
if (!content.trim()) {
throw new Error('任务内容不能为空');
}
const newTodo = new TodoItem(content);
this.todoList.push(newTodo);
return newTodo;
}
}
删除任务方法
删除任务通过任务的唯一id匹配,从数组中移除对应的任务实例。
class TodoList {
constructor() {
this.todoList = [];
}
addTodo(content) {
if (!content.trim()) {
throw new Error('任务内容不能为空');
}
const newTodo = new TodoItem(content);
this.todoList.push(newTodo);
return newTodo;
}
// 根据id删除任务
deleteTodo(id) {
const index = this.todoList.findIndex(item => item.id === id);
if (index === -1) {
throw new Error('未找到对应任务');
}
this.todoList.splice(index, 1);
}
}
切换任务完成状态
调用TodoItem实例的toggleStatus方法即可切换状态。
class TodoList {
constructor() {
this.todoList = [];
}
addTodo(content) {
if (!content.trim()) {
throw new Error('任务内容不能为空');
}
const newTodo = new TodoItem(content);
this.todoList.push(newTodo);
return newTodo;
}
deleteTodo(id) {
const index = this.todoList.findIndex(item => item.id === id);
if (index === -1) {
throw new Error('未找到对应任务');
}
this.todoList.splice(index, 1);
}
// 切换任务完成状态
toggleTodoStatus(id) {
const todo = this.todoList.find(item => item.id === id);
if (!todo) {
throw new Error('未找到对应任务');
}
todo.toggleStatus();
}
// 获取所有任务
getAllTodos() {
return [...this.todoList];
}
}
结合DOM实现页面交互
完成类的逻辑后,我们可以结合DOM操作,把类的功能对接到页面上,实现可视化的待办事项列表。
// 初始化待办列表实例
const myTodoList = new TodoList();
// 获取DOM元素
const todoInput = document.querySelector('#todo-input');
const addBtn = document.querySelector('#add-btn');
const todoContainer = document.querySelector('#todo-list');
// 渲染任务列表
function renderTodoList() {
todoContainer.innerHTML = '';
const todos = myTodoList.getAllTodos();
todos.forEach(todo => {
const li = document.createElement('li');
li.className = todo.isCompleted ? 'completed' : '';
li.innerHTML = `
<span>${todo.content}</span>
<button class="toggle-btn" data-id="${todo.id}">${todo.isCompleted ? '标记未完成' : '标记完成'}</button>
<button class="delete-btn" data-id="${todo.id}">删除</button>
`;
todoContainer.appendChild(li);
});
}
// 添加任务事件
addBtn.addEventListener('click', () => {
try {
myTodoList.addTodo(todoInput.value);
todoInput.value = '';
renderTodoList();
} catch (err) {
alert(err.message);
}
});
// 委托处理列表内按钮点击
todoContainer.addEventListener('click', (e) => {
const target = e.target;
const id = target.dataset.id;
if (target.classList.contains('toggle-btn')) {
try {
myTodoList.toggleTodoStatus(id);
renderTodoList();
} catch (err) {
alert(err.message);
}
}
if (target.classList.contains('delete-btn')) {
try {
myTodoList.deleteTodo(id);
renderTodoList();
} catch (err) {
alert(err.message);
}
}
});
对应的基础HTML结构如下,注意标签名称需要转义展示说明:
<div class="todo-app">
<input type="text" id="todo-input" placeholder="请输入待办任务">
<button id="add-btn">添加任务</button>
<ul id="todo-list"></ul>
</div>
<style>
.completed span {
text-decoration: line-through;
color: #999;
}
</style>
总结
通过JavaScript类构建待办事项列表,我们把任务数据和操作逻辑封装在类中,页面交互部分只需要调用类的实例方法即可,代码结构清晰,后续如果要添加本地存储、任务筛选等功能,只需要在类中扩展对应方法,不需要修改大量原有逻辑。这种方式也更符合面向对象的编程思想,适合中小型前端项目的结构组织。
JavaScript待办事项列表类面向对象编程修改时间:2026-07-12 06:03:24