我正在创建一个待办事项列表,我遵循tutorial来将项目保存到本地存储中,但是现在我很难弄清并理解如何获取代码以从本地存储中删除项目。当我按照教程进行操作时,添加到本地存储的所有项目都具有相同的密钥。 这是我的一些代码: HTML:
<h1>My Check List App</h1>
<h2 class="List Name"> Creating My App</h2>
<input type="text" id="the-input" class="the-input-class" placeholder="Write your tasks here...">
<span class="create-button">Create Task</span>
</div>
<ul id="the-ul" class="the-ul-list">
<li id="the-li" class="task">Complete Sprint One</li>
<li id="the-li" class="task">Complete Css</li>
<li id="the-li" class="task">Finish Sprint Two</li>
</ul>
</div>
JavaScript:
//removing tasks from list
var myList = document.getElementsByTagName('li');
var index;
for (index = 0; index < myList.length; index++){
var aSpanTag = document.createElement("SPAN");
var someTxt = document.createTextNode("\u00D7");
aSpanTag.className = "close";
aSpanTag.appendChild(someTxt);
myList[index].appendChild(aSpanTag);
}
var closeButton = document.getElementsByClassName("close");
for (i = 0; i < closeButton.length; i++){
closeButton[i].addEventListener('click', function(){
var theDiv = this.parentElement;
theDiv.style.display = "none";
})
}
//Adding tasks to localStorage
const submit = document.querySelector('.create-button');
const taskList = document.querySelector('.the-ul-list');
const taskInput = document.querySelector('.the-input-class');
function template(data){
taskList.insertAdjacentHTML("beforeend", `
<ul id="the-ul" class="the-ul-list">
<li id="the-li" class="task">${data.task}<span class ="close">x</span></li>
</ul>`);
}
function appendTask(event){
const data = {
task: taskInput.value,
}
event.preventDefault();
//if comment value is smaller than 1, submit will not work
if (taskInput.value.length < 1) return;
template(data);
taskInput.value ="";
// saving the tasks to localStorage
localStorage.setItem('taskItems', taskList.innerHTML)
}
submit.addEventListener('click', appendTask, false);
const saved = localStorage.getItem('taskItems');
if (saved) {
taskList.innerHTML = saved;
}
对不起,如果格式不好,这是我第一次在这里提问。
编辑:有人说我应该将其更改为数组,我将如何使用当前拥有的代码来执行此操作?
答案 0 :(得分:1)
您可以使用数组来从本地存储中检索数组,然后解析数据并推送新元素。
let saved = localStorage.getItem('taskItems');
if(!saved) {
//checking if we are doing it for the firsttime
const data = [taskList.innerHTML];
localStorage.setItem('tasksItems',JSON.stringify(data));
}
else {
const data = JSON.parse(saved);
saved.push(taskList.innerHTML);
localStorage.setItem('tasksItems',JSON.stringify(data));
}