请帮助我将输入内容存储在本地存储中。
var ul = document.getElementById('list');
var li;
var addButton = document.getElementById('add');
addButton.addEventListener('click', addItem);
var removeButton = document.getElementById('remove');
removeButton.addEventListener('click', removeItem)
function addItem() {
//console.log("Add button clicked");
var input = document.getElementById('input');
var item = input.value;
ul = document.getElementById('list');
var textnode = document.createTextNode(item)
localStorage.setItem('addItem', '');
console.log(localStorage.getItem('addItem'));
if (item === '') {
return false;
//add a p tag and assign a value of "enter yor todo"
} else {
//create li
li = document.createElement('li');
//create checkbox
var checkbox = document.createElement('input')
checkbox.type = 'checkbox';
checkbox.setAttribute('id', 'check');
//create label
var label = document.createElement('label');
label.setAttribute('for', 'item') //optional
//add these elements on web page
ul.appendChild(label);
li.appendChild(checkbox);
label.appendChild(textnode);
li.appendChild(label);
ul.insertBefore(li, ul.childNodes[0]);
setTimeout(() => {
li.className = 'visual';
}, 2);
input.value = '';
}
}
function removeItem() {
li = ul.children
for (let index = 0; index < li.length; index++) {
while (li[index] && li[index].children[0].checked) {
ul.removeChild(li[index])
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Simple todo Apllication</title>
</head>
<body>
<div id="container">
<div class="controls">
<h1>My Awesome TODO</h1>
<input type="text" id="input"><br>
<button type="button" id="add">ADD TODO</button>
<button type="button" id="remove">Remove TODO</button>
</div>
<ul id="list">
<li class="mycheck">
<input type="checkbox" id="check"><label>Go to Gym</label>
</li>
<li class="mycheck">
<input type="checkbox" id="check" checked><label>Record youtube video</label>
</li>
<li class="mycheck">
<input type="checkbox" id="check" checked><label>Record youtube video</label>
</li>
<li class="mycheck">
<input type="checkbox" id="check" checked><label>Record youtube video</label>
</li>
<li class="mycheck">
<input type="checkbox" id="check" checked><label>Record youtube video</label>
</li>
</ul>
</div>
<script src="todo.js"></script>
</body>
</html>
答案 0 :(得分:0)
要将数据存储在本地存储中,可以使用localStorage.setItem
方法。它有2个参数。第一个是keyName
,即用来存储数据的名称。第二个是keyValue
,它是存储在存储器中的值。
您可以详细了解here。
以下代码将示例TODO存储在本地存储中。
localStorage.setItem("sampleTodo", JSON.stringify({"title": "sample", "description": "It is a sample Todo", "completed": false}));
请注意,我使用JSON.stringify来存储JSON对象。
答案 1 :(得分:0)
您可以简单地做到这一点
localStorage.keyName = 'value';
答案 2 :(得分:0)