我正在使用DOM方法构建一个简单的JavaScript待办事项列表,并尝试为列表项实现localStorage
。当同时添加和删除项目时,localStorage
似乎可以正常工作。但是,在呈现列表项之前,将单词undefined
扔到屏幕上。知道为什么会这样吗?非常感激!
JS:
var ul = document.getElementById("myUl");
function add() {
var item = document.getElementById("newItem").value;
var itemTxt = document.createTextNode(item);
var li = document.createElement("li");
var btn = document.createElement("button");
var btnx = document.createTextNode("x");
btn.setAttribute("onclick", "remove()");
btn.appendChild(btnx);
li.appendChild(itemTxt);
li.appendChild(btn);
ul.appendChild(li);
}
function remove() {
var task = this.event.currentTarget.parentNode;
ul.removeChild(task);
}
ul.innerHTML = localStorage["list"];
setInterval(function(){
localStorage["list"] = ul.innerHTML;
}, 1000);
HTML:
<input id="newItem" />
<button onclick="add()">add</button>
<ul id="myUl">New List</ul>
答案 0 :(得分:1)
我更新了带有注释的代码:
var ul = document.getElementById("myUl");
function add() {
var item = document.getElementById("newItem").value;
var itemTxt = document.createTextNode(item);
var li = document.createElement("li");
var btn = document.createElement("button");
var btnx = document.createTextNode("x");
btn.setAttribute("onclick", "remove()");
btn.appendChild(btnx);
li.appendChild(itemTxt);
li.appendChild(btn);
ul.appendChild(li);
localStorage["list"] = ul.innerHTML // updating localstorage
}
function remove() {
var task = this.event.currentTarget.parentNode;
ul.removeChild(task);
localStorage["list"] = ul.innerHTML // updating localstorage
}
if (localStorage["list"]) { // checking, if there is something in localstorage
ul.innerHTML = localStorage["list"];
}
演示:https://codepen.io/anon/pen/dQpwpz
注意事项:将html
放入localStorage
并不是最佳做法,但我相信您知道。