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

待办事项Done按钮功能异常,求基于现有代码的修复方案

修复To-Do List中Done按钮点击失效问题

问题根源

所有新增任务的Done按钮都使用了相同的id="Done",但DOM规范要求元素id必须唯一。document.getElementById("Done")只会返回页面中第一个匹配该id的元素,导致后续添加的任务按钮无法正确绑定点击事件——只有第一个任务的Done按钮能正常工作,后面的点击毫无响应。

修复方案(无需整体重构)

只需修改todoList函数中按钮的创建与事件绑定逻辑,规避重复id问题,直接针对当前任务的按钮绑定事件:

  1. 移除按钮的重复id,改用class或直接不设置标识
  2. 通过当前任务的<li>元素直接查找内部的Done按钮,确保绑定的是当前任务对应的按钮

修改后的完整代码

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Document</title>
</head>

<body>
  <h1>To-Do List</h1>
  <form id="todoForm">
    <input id="todoInput" />
    <button type="button" onclick="todoList()">New</button>
    <button type="button" onclick="">Retrieve</button>
  </form>
  <ol id="todoList"></ol>
  <script>
    var todos = [];
    var removed = [];

    function todoList() {
      var item = document.getElementById("todoInput").value;
      if (!item.trim()) return; // 可选:过滤空任务
      todos.push(item);

      var newItem = document.createElement("li");
      // 移除重复id,改用class标识按钮(也可直接不设class)
      newItem.innerHTML = item + ' <button class="done-btn">Done</button>';
      document.getElementById("todoList").appendChild(newItem);

      // 从当前li元素内直接获取按钮,确保绑定当前任务的按钮
      const donebtn = newItem.querySelector('.done-btn');
      donebtn.addEventListener("click", function() {
        removetodo(newItem, item)
      });

      // 可选:清空输入框,提升体验
      document.getElementById("todoInput").value = '';
    }


    function removetodo(item, tasktext) {
      const tasklist = document.getElementById("todoList");
      tasklist.removeChild(item);
      removed.push(tasktext);
    }
  </script>
</body>

</html>

关键修改点说明

  • 移除了按钮的重复id="Done",改用class="done-btn"(class允许重复使用)
  • 使用newItem.querySelector('.done-btn')获取当前任务对应的按钮,替代全局id查找,确保每个按钮都能正确绑定点击事件
  • 新增了空任务过滤和输入框清空的可选逻辑,优化用户操作体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:10:31