[英]How do I save information for a user of a website?
这是我的代码(在网站上): https : //stick-z.github.io/或者,这里是 HTML 和 JavaScript:
<!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>Poster</title>
</head>
<body>
<h1>To-Do:</h1>
<ul id="list">
<li>Hello</li>
<li>This is</li>
<li>A test</li>
</ul>
<div class="input">
<input id="form" type="text"></input>
<button id="enter">Add</button>
</div>
<script src="app.js"></script>
</body>
</html>
const list = document.getElementById("list")
const enter = document.getElementById("enter")
enter.addEventListener("click", add => {
var input = document.getElementById("form").value
var node = document.createElement("LI")
var text = document.createTextNode(input)
node.appendChild(text)
list.appendChild(node)
})
document.querySelector('#list').addEventListener('click', function({target}) {
if (target.matches('li'))
target.remove()
}, false);
我希望能够重新加载页面,并将我之前制作的“待办事项”保留在那里。 我该如何实现?
以下代码利用本地存储来保存列表内容并在网站重新加载时加载它。
我添加了localStorage.setItem('items', document.getElementById("list").innerHTML);
到每个事件侦听器的末尾以更新列表并添加了list.innerHTML = localStorage.getItem("items");
在 JavaScript 文件的末尾加载网页时加载保存的列表。
我用工作代码制作了一个jsfiddle 。
您没有在 JavaScript 文件的每一行后放置分号 ( ;
),这是不好的做法,并且当 input 元素没有结束标记时,您在 HTML <input>
元素上放置了结束标记。
<!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>Poster</title>
</head>
<body>
<h1>To-Do:</h1>
<ul id="list">
<li>Hello</li>
<li>This is</li>
<li>A test</li>
</ul>
<div class="input">
<input id="form" type="text">
<button id="enter">Add</button>
</div>
<script src="app.js"></script>
</body>
</html>
const list = document.getElementById("list");
const enter = document.getElementById("enter");
enter.addEventListener("click", add => {
var input = document.getElementById("form").value;
var node = document.createElement("LI");
var text = document.createTextNode(input);
node.appendChild(text);
list.appendChild(node);
localStorage.setItem('items', document.getElementById("list").innerHTML);
})
document.querySelector('#list').addEventListener('click', function({target}) {
if (target.matches('li'));
target.remove();
localStorage.setItem('items', document.getElementById("list").innerHTML);
}, false);
list.innerHTML = localStorage.getItem("items");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.