【发布时间】:2019-11-16 01:56:35
【问题描述】:
我创建了一个简单的网站来添加和删除待办事项列表中的项目,用户可以在其中输入项目并添加到当前列表中。我希望用户能够保存当前列表,当他们从同一个浏览器打开时,他们可以看到上次编辑的列表。换句话说:使用本地存储功能来实现这一点(不使用任何服务器端脚本或数据库)。不知道如何通过用户点击保存按钮来实现这一点。这是我的html代码:
<html>
<body>
<div id="myDIV" class="header">
<h1>My To Do List</h1>
<input type="text" id="myInput" placeholder="Add to the list">
<span onclick="addToList()" class="addBtn">Add</span>
</div>
<ul id="myUL">
<li>Go to grocery</li>
<li>Pay bills</li>
<li>Go to class</li>
<li>Clean home</li>
<li>Do laundry</li>
<li>Do homework</li>
</ul>
<button onclick="saveList()" type="button">Save</button>
<script src="index.js"></script>
</body>
这是我的 JavaScript 代码:
function addToList() {
var li = document.createElement("li");
var inputValue = document.getElementById("myInput").value;
var tn = document.createTextNode(inputValue);
li.appendChild(tn);
if (inputValue === '') {
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("myInput").value = "";
var span = document.createElement("SPAN");
var txt = document.createTextNode("\u00D7");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
我想定义 saveList() 函数以允许用户保存列表,以便他们可以关闭浏览器并使用从本地存储中检索的已保存数据重新打开。希望这是有道理的。
【问题讨论】:
-
这能回答你的问题吗? Storing Objects in HTML5 localStorage
标签: javascript html