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

使用JavaScript开发待办清单:实现checkbox勾选/取消时添加/移除class

实现待办清单Checkbox勾选状态同步Class的功能

以下是完整的实现方案,包含动态创建待办项、Checkbox状态切换时自动添加/移除指定Class的逻辑:

基础HTML结构

先搭好页面骨架,包含输入框、添加按钮和待办项容器:

<input type="text" id="todoInput" placeholder="输入待办事项">
<button id="addTodoBtn">添加待办</button>
<div id="todoContainer"></div>

CSS样式(示例)

定义需要切换的Class样式,比如勾选后文本变灰并加删除线:

.completed {
  color: #999;
  text-decoration: line-through;
}
.todo-item {
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

JavaScript逻辑

实现添加待办项、绑定Checkbox状态切换事件:

const todoInput = document.getElementById('todoInput');
const addTodoBtn = document.getElementById('addTodoBtn');
const todoContainer = document.getElementById('todoContainer');

// 添加待办项的函数
function addTodo() {
  const todoText = todoInput.value.trim();
  if (!todoText) return;

  // 创建待办项容器
  const todoItem = document.createElement('div');
  todoItem.className = 'todo-item';

  // 创建Checkbox
  const checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  // 绑定状态切换事件
  checkbox.addEventListener('change', function() {
    // 切换目标元素的Class,这里选择待办文本元素
    todoTextElement.classList.toggle('completed', this.checked);
  });

  // 创建待办文本
  const todoTextElement = document.createElement('span');
  todoTextElement.textContent = todoText;

  // 创建删除按钮
  const deleteBtn = document.createElement('button');
  deleteBtn.textContent = '删除';
  deleteBtn.addEventListener('click', function() {
    todoContainer.removeChild(todoItem);
  });

  // 组装待办项
  todoItem.appendChild(checkbox);
  todoItem.appendChild(todoTextElement);
  todoItem.appendChild(deleteBtn);
  todoContainer.appendChild(todoItem);

  // 清空输入框
  todoInput.value = '';
}

// 绑定添加按钮点击事件
addTodoBtn.addEventListener('click', addTodo);
// 支持回车添加
todoInput.addEventListener('keypress', function(e) {
  if (e.key === 'Enter') addTodo();
});

关键逻辑说明

  • 在创建Checkbox时,直接给它绑定change事件,当勾选状态变化时,用classList.toggle()方法自动添加或移除completed类,第二个参数this.checked控制是否添加Class(true则添加,false则移除)。
  • 如果待办项数量较多,推荐用事件委托优化:给todoContainer绑定事件,通过事件冒泡处理所有子Checkbox的状态变化,不需要为每个新创建的Checkbox单独绑定事件,性能更优。

事件委托优化的代码示例:

// 事件委托:给容器绑定事件,处理所有子Checkbox的状态变化
todoContainer.addEventListener('change', function(e) {
  if (e.target.type === 'checkbox') {
    // 找到当前Checkbox对应的文本元素(这里是下一个兄弟元素)
    const textElement = e.target.nextElementSibling;
    textElement.classList.toggle('completed', e.target.checked);
  }
});

使用这种方式时,需要删除创建Checkbox时绑定的addEventListener代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 01:55:19