[英]How can i remove a localStorage value from a string, without hardcoding the value?
我搞砸了JS和localStorage,創建了一個待辦事項列表。 單擊列表中的項目時,它將更改其CSS類, 應將其從localStorage中刪除。 該項目的價值由用戶決定,所以我無法硬編碼
localStorage.removeItem('Do the dishes');
例如。
我嘗試這樣做:
localStorage.removeItem(ev.target.innerText);
(下面是較長的版本)。 它不會給我一個錯誤,但也不會從localStorage中刪除該項目。
var taskList = document.querySelector('ul');
taskList.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
let tasks;
if(localStorage.getItem('tasks') === null ){
tasks = [];
}
else {
tasks = JSON.parse(localStorage.getItem('tasks'));
console.log("TaskList Is Not empty");
tasks.forEach(function(task, index){
if(ev.target.innerText === task){
localStorage.removeItem(ev.target.innerText);
console.log("Removed");
}
else{
console.log("Else Executed");
}
}
所有任務都添加到名為“任務”的localStorage項中:
function storeTaskInLocalStorage(newTask){
let tasks;
if(localStorage.getItem('tasks') === null ){
tasks = [];
}else{
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.push(newTask);
localStorage.setItem('tasks', JSON.stringify(tasks));
}
如前所述,該項目應從 localStorage中刪除,但不是。 這可能是我的代碼中的錯誤,但是我似乎無法在互聯網上找到其他任何方式,因此,我們將不勝感激!
如果需要整個項目進行故障排除或其他任何事情,請讓我知道,我可以將其上傳到codePen或其他東西:)
那應該做的工作:
var taskList = document.querySelector('ul');
taskList.addEventListener('click', function (ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
let tasks;
if (localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
console.log('TaskList Is Not empty');
const taskId = tasks.indexOf(ev.target.innerText);
if (taskId !== -1) {
tasks.splice(taskId, 1);
localStorage.setItem('tasks', JSON.stringify(tasks));
}
}
}
});
我希望tasks
是一個字符串數組,您可以在其中存儲待辦事項-否則請告訴我,以便我修改代碼。
您設置和刪除的鍵之間有錯誤...您嘗試
localStorage.removeItem(ev.target.innerText);
而您設置的密鑰是:
localStorage.getItem('tasks')
您應該做的是編輯剛解析的數組,並在JSON字符串化后再次保存在同一鍵下,或者保存在其他鍵下
您需要將其設置為
localStorage.setItem('taskName', 'Do the dishes');
然后您可以將其刪除為
localStorage.removeItem('taskName');
如果您有一系列物品,可以做
const tasks= [];
task.push('Do the dishes');
task.push('Wash the car');
localStorage.setItem('taskName', JSON.stringify(task));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.