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

JavaScript待办应用编辑按钮故障求助:仅首个任务可正常编辑

问题原因及解决方法

核心问题

  1. 编辑按钮未关联对应任务索引:原editItem()函数没有接收任务的索引参数,且用document.querySelector(".todoContent")只会获取页面中第一个匹配的输入框,导致所有编辑按钮都操作第一个任务。
  2. 未更新数据源:编辑完成后仅修改了输入框的值,没有同步更新todos数组中对应任务的内容,导致 localStorage 里的数据没变化,新增任务或刷新页面后内容回滚。
  3. 重复绑定事件:每次调用editItem()都给输入框绑定blur事件,会造成事件重复触发,引发异常。

具体修改步骤


1. 给编辑按钮传入任务索引

在showList()函数的模板字符串中,把编辑按钮的点击事件改成传入当前任务的索引,让每个按钮明确自己要编辑的任务:

// 原代码
<button type="button" class="btn btn-secondary col-12" onClick="editItem()">Edit</button>

// 修改后
<button type="button" class="btn btn-secondary col-12" onClick="editItem(${index})">Edit</button>

2. 重写editItem()函数,关联对应任务

  • 接收索引参数,通过索引定位到对应任务的输入框
  • 移除只读属性并聚焦输入框
  • 绑定一次性blur事件,更新todos数组和 localStorage,避免重复触发
function editItem(index) {
    const taskInputs = document.querySelectorAll(".todoContent");
    const taskInput = taskInputs[index];
    
    if (!taskInput) return;

    taskInput.removeAttribute('readonly');
    taskInput.focus();

    taskInput.addEventListener("blur", (e) => {
        e.target.setAttribute('readonly', true);
        // 更新数据源中对应任务的内容
        todos[index].task = e.target.value;
        // 同步到localStorage
        localStorage.setItem('todos', JSON.stringify(todos));
        showList();
    }, { once: true });
}

3. 清理冗余代码

删掉showList()中没用的const taskName = document.querySelector(".todoContent")代码,避免混淆。


修改后的完整JavaScript代码

const todoForm = document.getElementById("todo-form")

window.addEventListener("load", () => {
    todos = JSON.parse(localStorage.getItem("todos")) || []

    todoForm.addEventListener("submit", (e) => {
        e.preventDefault()
        if (e.target.elements.newTask.value != "") {
            const todo = {
                task: e.target.elements.newTask.value,
                category: e.target.elements.category.value
            }

            todos.push(todo);

            localStorage.setItem("todos", JSON.stringify(todos));

            e.target.reset()

            showList()
        }
    })

    showList();
})

function showList() {
    let outPut = '';
    let taskListShow = document.querySelector(".todoList")

    todos.forEach((data, index)=> {
        outPut += `
        <div class="row todoList mb-3">
            <div class="col-10 col-lg-8 col-md-7 col-sm-6">
                <input class="todoContent no-border text-white text-center" value="${data.task}" readonly>
            </div>
            <div class="col">
                <div class="row action">
                    <div class="col-6">
                        <button type="button" class="btn btn-secondary col-12" onClick="editItem(${index})">Edit</button>
                    </div>
                    <div class="col-6">
                        <button type="button" class="btn btn-danger col-12" onClick="deleteItem(${index})">Delete</button>
                    </div>       
                </div>
            </div>
        </div>`
    });
    taskListShow.innerHTML = outPut;
}

function deleteItem(index) {
    todos.splice(index, 1)
    localStorage.setItem("todos", JSON.stringify(todos))
    showList()
}

function editItem(index) {
    const taskInputs = document.querySelectorAll(".todoContent");
    const taskInput = taskInputs[index];
    
    if (!taskInput) return;

    taskInput.removeAttribute('readonly');
    taskInput.focus();

    taskInput.addEventListener("blur", (e) => {
        e.target.setAttribute('readonly', true);
        todos[index].task = e.target.value;
        localStorage.setItem('todos', JSON.stringify(todos));
        showList();
    }, { once: true });
}

修改后,每个编辑按钮会精准操作对应任务,编辑内容会同步到数据源和 localStorage,新增任务也不会导致内容回滚。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:48:17