我正在努力编辑 ToDo 应用程序上的任务并更新 localstorage 对象中的更改。我试过 contenteditable 来编辑 UI 上的文本。但是,我无法更新对 localstorage 数组的更改。这是我正在使用的代码。任何建议将不胜感激!// Edit taskconst eidtTask = (e) => { // Array of objects of tasks const tasks = JSON.parse(localStorage.getItem('tasks')); if(e.target.classList.contains('edit')) { // When I click edit button I want to edit the task and update the value on localstorage array as well } localStorage.setItem('tasks', JSON.stringify(tasks));};
1 回答

撒科打诨
TA贡献1934条经验 获得超2个赞
在 HTML 元素中有一个数据属性,并oldValue在本地存储数据中有一个可以更新本地存储的数据
一旦用户点击提交或完成编辑,更改 HTML 数据属性和oldValue本地存储。
// Edit task
const editTask = (e) => {
// Array of objects of tasks
const tasks = JSON.parse(localStorage.getItem('tasks'));
if (e.target.classList.contains('edit')) {
for (const task of tasks) {
if (task.oldValue === e.target.getAttribute('data-foo')) {
task.value = e.target.value;
}
}
}
localStorage.setItem('tasks', JSON.stringify(tasks));
};
添加回答
举报
0/150
提交
取消