我试图将用户输入添加到数组中。我似乎不知道如何实现这一目标。我花了几个小时试图弄清楚到底该怎么做。我还希望将这个“待办事项列表”保存到我的本地存储中,我对试图解决这两个问题同样感到沮丧。
任何有关如何从用户输入添加到数组和/或如何将其放入本地存储的建议或指导将不胜感激。我花了相当长的时间才走到这一步。感谢您的帮助!非常感谢。
Javascript
var theList = [];
function todoList() {
var item = document.getElementById('todoInput').value;
var text = document.createTextNode(item);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var newItem = document.createElement("li");
newItem.appendChild(checkbox);
newItem.appendChild(text);
document.getElementById("todoList").appendChild(newItem)
return clear();
}
function clear() {
todoInput.value = "";
}
console.log(theList);
HTML
<h1>To Do List:<h1>
<input id="todoInput" type="text">
<button type="button" onclick="todoList()">Add Item</button>
</form>
<ol id="todoList">
</ol>
<script src="todo.js"></script>
最佳答案
要添加新创建的列表项,只需将 theList.push(item)
添加到 todoList()
函数即可。
要将 var theList = []
数组保存到 localStorage,请使用:
localStorage.setItem("todoList", JSON.stringify(theList));
并使用它来检索 localStroage 对象:
var storedTodoList = JSON.parse(localStorage.getItem("todoList"));
请参阅下面的代码片段:
<h1>To Do List:</h1>
<input id="todoInput" type="text">
<button type="button" onclick="todoList()">Add Item</button>
<ol id="todoList">
</ol>
<script>
var theList = [];
function todoList() {
var item = document.getElementById('todoInput').value;
var text = document.createTextNode(item);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "name";
checkbox.value = "value";
var newItem = document.createElement("li");
newItem.appendChild(checkbox);
newItem.appendChild(text);
document.getElementById("todoList").appendChild(newItem);
theList.push(item); // This adds the item to theList[]
//localStorage.setItem("todoList", JSON.stringify(theList)); // Set localStorage object
//var storedTodoList = JSON.parse(localStorage.getItem("todoList")); // Get localStorage object
console.log(theList);
return clear();
}
function clear() {
todoInput.value = "";
}
</script>
<!-- <script src="todo.js"></script> -->
希望这有帮助。
关于Javascript 待办事项列表应用程序推送到数组/本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42384652/