使用JS将值附加到新数组中

时间:2018-10-10 09:49:07

标签: javascript html local-storage

我正在尝试使用HTML,JS和本地存储来构建表单(更多用于个人学习):

  1. 接受用户的输入
  2. 显示来自用户的输入
  3. 将数据存储在本地存储中
  4. 为用户提供删除项目或删除所有内容的选项

问题:

  • 本地存储始终存储输入的最新值,而不是整个数组。由于某种原因,push数组未附加所有值。我想念什么?
  • 删除线一次就起作用,但不是每个选项都起作用。每个选项的处理方式是什么?

function display(){
      var master_list = [];
      var data = document.getElementById('to_do').value;
      master_list.push(data);
      document.getElementById('form_data').innerHTML += "<li>"+ data +"</li>";
      console.log("data is "+ data);
      console.log("master list is "+ master_list);
      // storeData(master_list);
    }
    
    function remove(){
      var list = document.getElementById('form_data').innerText;
      // console.log("the data is " + list);
      document.getElementById('form_data').innerHTML = list.strike();
    
    }
    
    function storeData(master_list){
      localStorage.setItem("master_list", JSON.stringify(master_list));
    
    }
 <!DOCTYPE html>
    <html lang="en">
    
      <head>
        <meta charset="utf-8">
        <title>The To-do Application</title>
        <script src="to_do_app.js" charset="utf-8"></script>
      </head>
    
      <body>
        <h1>Welcome to the To-Do application</h1>
        <label>Enter your to-do item: </label>
        <input type="text" id="to_do" placeholder="eg: groceries">
        <button onclick=display()> Add </button>
        <h3>Added Items are:</h3>
        <div id="form_data"></div>
        <br>
        <button onclick=remove()> Clear All </button>
        <!-- <h6>Note: To remove please click on the item</h6> -->
      </body>
    
    </html>



    

1 个答案:

答案 0 :(得分:2)

您必须使用master_list检查localStorage.getItem项是否已经存在于localStorage中(如果所请求的项不存在,它将自动返回null)

const storeData= master_list => {
    let item = localStorage.getItem("master_list");
    if ( ! item ) {
        localStorage.setItem("master_list", master_list);
        return;
    }
    item = JSON.parse("master_list");
    item.concat(master_list); // or master_list.concat(item) depending on your needs
    localStorage.setItem("master_list", item);
};