问题描述
- saveButton 有 2 个用于“单击”的事件处理程序,1 个用于更新,1 个用于添加新任务
- editThis() 是编辑图标的事件处理程序,它将选定的任务详细信息复制到输入字段以进行更新。saveButton 附加了匿名事件处理程序,该处理程序将更新保存在 localStorage,UI
- 问题所有单击“编辑图标”的任务都得到更新而不是 1,并且除了更新之外,新任务也得到添加。
/* default value is 0, indicates that new task should be added when saveButton is clicked */
let currentOperation = 0;
function editThis(event) {
currentOperation = 1;
let saveButton = document.getElementsByClassName("form__submit")[0];
// this variable is used to identify which task needs to be updated
let currentItemId = event.target.parentNode.dataset.dataId;
// each task is stored in localStorage as task[i]= JSONObject.stringify()
let selectedTask = JSON.parse(localStorage.getItem("task[" + currentItemId + "]"));
// task details are transferred to input fields to edit
inputs[0].value = selectedTask.title;
inputs[1].value = selectedTask.date;
inputs[2].value = selectedTask.status;
saveButton.addEventListener("click", function() {
if (currentOperation == 1) {
//inputs[x] = document.getElementsByClassName("input")[x]
let updatedObject = { title: inputs[0].value, date: inputs[1].value, status: inputs[2].value };
localStorage.setItem("task[" + currentItemId + "]", JSON.stringify(updatedObject));
document.getElementsByClassName("todo-container")[currentItemId].firstChild.nodeValue = updatedObject.title + " " + updatedObject.date + " " + updatedObject.status;// .todo-container has 2 children nodes, 1st contains task details and 2nd contains edit icon to which editThis event handler is attached
setTimeout(function () { currentOperation = 0; }, 20000);
}
});
}
此图像显示放置编辑图标、保存按钮、待办事项容器
标签: javascripthtmlevent-handlingdom-events
解决方案
推荐阅读