我一直在尝试创建一个待办事项列表,但不断遇到不同的问题。现在我正在尝试从本地存储中提取数组,因此当我刷新浏览器时,它将显示待办事项列表。我已经尝试过了,我知道我需要做一些类似的事情
localStorage.getItem
但我不知道如何去做。我认为我需要将其放入不同的函数中,然后在 JavaScript 末尾调用该不同的函数。我还认为我需要为此使用 for 循环。我想我可能需要重做当前的 JavaScript,但不知道从这里该去哪里。
JavaScript
var masterList = [];
function addToList(){
var task = document.getElementById('todoInput').value;
var entry = document.createElement('li'); //2
var list = document.getElementById('orderedList'); //2
entry.appendChild(document.createTextNode(task)); //2
list.appendChild(entry); //2
masterList.push(task);
localStorage.setItem('masterList', JSON.stringify(masterList));
console.log(task);
console.log(masterList);
clearInput();
}
function clearInput() {
todoInput.value = "";
}
console.log((localStorage.getItem('masterList')));
HTML
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1>To Do List:<h1>
<input id="todoInput" type="text">
<button type="button" onclick="addToList()">Add Item</button>
<ol id='orderedList'></ol>
<script src="todo.js"></script>
</body>
CSS
ol li {
background: lightgray;
text-align: left;
}
ol li:nth-child(odd){
background: lightblue;
text-align: left
text: 10%;
}
input[type=text]{
width: 20%;
border: 2px solid black;
background-color: rgba(255, 0, 0, 0.2);
text-align: center;
}
h1{
text-align: center;
}
最佳答案
您必须在文档加载时调用一个函数,该函数将从 localStorage
获取 todo
列表。如果不存在,masterList
将变成一个空数组,并准备好在其中存储 todos
。
注意:检查它是否有效,因为由于 SO 上的 cors 阻塞,我无法测试它。
var masterList;
window.onload = function(){
masterList = JSON.parse(localStorage.getItem('masterList')); //get data from storage
if (masterList !== null) { //if data exist (todos are in storage)
masterList.forEach(function(v){ //append each element into the dom
var task = v;
var entry = document.createElement('li'); //2
var list = document.getElementById('orderedList'); //2
entry.appendChild(document.createTextNode(task)); //2
list.appendChild(entry); //2
})
} else { //if nothing exist in storage, keep todos array empty
masterList = [];
}
}
function addToList(){
var task = document.getElementById('todoInput').value;
var entry = document.createElement('li'); //2
var list = document.getElementById('orderedList'); //2
entry.appendChild(document.createTextNode(task)); //2
list.appendChild(entry); //2
masterList.push(task);
localStorage.setItem('masterList', JSON.stringify(masterList));
console.log(task);
console.log(masterList);
clearInput();
}
function clearInput() {
todoInput.value = "";
}
关于javascript - 在 OL 中的页面加载/刷新时显示本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42539746/