Javascript 待办事项列表应用程序推送到数组/本地存储

标签 javascript html arrays local-storage push

我试图将用户输入添加到数组中。我似乎不知道如何实现这一目标。我花了几个小时试图弄清楚到底该怎么做。我还希望将这个“待办事项列表”保存到我的本地存储中,我对试图解决这两个问题同样感到沮丧。

任何有关如何从用户输入添加到数组和/或如何将其放入本地存储的建议或指导将不胜感激。我花了相当长的时间才走到这一步。感谢您的帮助!非常感谢。

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/

相关文章:

html - 你如何在 CSS 中将一个换行的 <nav> 菜单居中?

javascript - 如何使 Javascript 数组中的部分文本在不同时间显示?

javascript - 如何在二次曲线上跟踪坐标

javascript - 如何在一台 TURN 服务器出现故障时恢复 WebRTC 调用

javascript -/PM 用于在聊天室发送消息的正则表达式语法

将 Char* 转换为 Char* 数组

c# - 如何将玩家存储在数组中?

javascript - 如何实际计算奇偶校验是偶数还是奇数?

java - 在 Java HTML 感知组件中使用

javascript - 从代码中的其他地方调用 JQuery 事件作为函数...?