我正在尝试将本地存储添加到我的待办事项列表中。在刷新页面时,列表的内容确实会保留,但返回的值未定义。我怀疑这与我在底部调用addInput函数时缺少参数有关,但是我找不到解决方法。
此外,如果已切换选中的班级已打开并且该项目被划掉,是否可以存储班级信息?
非常感谢您能给我任何帮助。
有问题的代码如下:
https://codepen.io/david-webb/pen/yLeqydK
function saveTodos () {
let jsonstr = JSON.stringify(todos);
localStorage.setItem('todos', jsonstr);
}
function getTodos () {
localStorage.getItem('todoList')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (!todos) {
todos = [];
}
}
//cross out text on click
document.addEventListener('click', function(ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
saveTodos ();
}
});
getTodos ();
addInput ();
答案 0 :(得分:1)
请尝试以下操作:
<input type="text" style="font-size:25px;" id="input" placeholder="Write here">
<button id="addBtn">Add item</button>
<ul id="myUL">
</ul>
<script>
let todo = [];
document.getElementById('addBtn').addEventListener('click', function () {
let value = document.getElementById('input').value;
if (value) {
todo.push(value);
saveTodos()
addInput(value);
}
});
function addInput(text) {
//add list item on click
let listItem = document.createElement('li');
let list = document.getElementById('myUL');
let input = document.getElementById('input').value;
let textNode = document.createTextNode(text);
//create and append remove button
let removeBtn = document.createElement("BUTTON");
list.appendChild(removeBtn);
removeBtn.className = "removeBtn";
removeBtn.innerHTML = "Remove item";
listItem.appendChild(removeBtn);
list.appendChild(listItem);
listItem.appendChild(textNode);
document.getElementById("input").value = "";
removeBtn.addEventListener('click', removeItem);
//console.log(todo);
}
//remove list item on click
function removeItem() {
let item = this.parentNode.parentNode;
let parent = item.parentNode;
let id = parent.id;
let value = parent.innerText;
todo.splice(todo.indexOf(value, 1));
saveTodos();
this.parentNode.parentNode.removeChild(this.parentNode);
console.log(todo)
}
function saveTodos() {
let jsonstr = JSON.stringify(todo);
localStorage.setItem('todos', jsonstr);
}
function getTodos() {
localStorage.getItem('todos')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (todos && !todos.length) {
todos = [];
}
else{
if(todos){
for(var intCounter = 0; intCounter < todos.length; intCounter++){
addInput(todos[intCounter]);
}
}
}
}
//cross out text on click
document.addEventListener('click', function (ev) {
if (ev.target.tagName === 'LI') {
ev.target.classList.toggle('checked');
saveTodos();
}
});
getTodos();
// addInput();
</script>
在getTodos函数中调用addInput,以便在完成检索列表后立即打印出来。
这就是我所做的更改:
功能getTodos
function getTodos() {
localStorage.getItem('todos')
let jsonstr = localStorage.getItem("todos");
todos = JSON.parse(jsonstr);
if (todos && !todos.length) {
todos = [];
}
else{
if(todos){
for(var intCounter = 0; intCounter < todos.length; intCounter++){
addInput(todos[intCounter]);
}
}
}
}
注释了addInput()。