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

基于document.getElementById的Todo列表功能异常,求修复方案

修复后的可运行Todo列表实现

完整代码实现

HTML

<div id="jobList">
  <input id="jobInput" type="text" placeholder="输入待办事项">
  <button class="specialButton" id="job">添加</button>
</div>
<div id="todoContainer"></div> <!-- 专门存放todo项的容器 -->

CSS

.specialButton {
  background-color: navy;
  color: white;
  height: 25px;
  width: 75px;
  border-radius: 10px;
  border: none;
  transition-duration: 0.3s;
  margin-left: 8px;
}
.specialButton:hover {
  color: navy;
  background-color: white;
  border: solid 1px navy;
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
}

.todo-text {
  font-family: "Lucida Console", monospace;
  color: yellow;
  margin: 0;
}

.delete {
  width: 60px;
  height: 20px;
  background-color: red;
  color: white;
  border: none;
  cursor: pointer;
}
.delete:hover {
  background-color: darkred;
}

JavaScript

const addBtn = document.getElementById("job");
const jobInput = document.getElementById("jobInput");
const todoContainer = document.getElementById("todoContainer");
let cnt = 1;

addBtn.addEventListener('click', addJob);

function addJob() {
  const inputValue = jobInput.value.trim();
  if (!inputValue) return; // 空内容不添加

  // 创建todo项容器
  const todoItem = document.createElement('div');
  todoItem.className = 'todo-item';
  todoItem.id = `del${cnt}`;

  // 创建待办文本
  const todoText = document.createElement('p');
  todoText.className = 'todo-text';
  todoText.textContent = inputValue;

  // 创建删除按钮并绑定事件
  const deleteBtn = document.createElement('button');
  deleteBtn.className = 'delete';
  deleteBtn.textContent = '删除';
  deleteBtn.addEventListener('click', () => {
    todoItem.remove();
    console.log("已删除待办项");
  });

  // 组装并添加到容器
  todoItem.appendChild(todoText);
  todoItem.appendChild(deleteBtn);
  todoContainer.appendChild(todoItem);

  // 清空输入框
  jobInput.value = '';
  cnt++;
}

关键修改说明

  • DOM结构优化:新增todoContainer统一管理所有待办项,避免原代码中标签顺序混乱的问题。
  • 元素创建方式改进:用document.createElement替代字符串拼接插入HTML,更安全且便于事件绑定。
  • 事件绑定修复:删除按钮的事件采用箭头函数,确保点击按钮时才执行删除操作,而非立即触发。
  • 输入校验:添加空内容判断,避免创建无效的待办项。
  • 变量规范:使用const/let声明变量,避免全局变量污染。
  • 样式优化:给todo项添加flex布局,让文本和按钮对齐更美观,完善删除按钮的交互样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 14:43:14