簡體   English   中英

如何在一個 localStorage 鍵中存儲多個值?

[英]How can I store multiple values inside one localStorage key?

如何存儲localStorage值而不會丟失存儲在其上的最后一個值我編寫代碼以在每次單擊按鈕“插入新行”時從輸入中插入行到表中的數據,但是在填充表后我有問題我想使用表的數據插入到SQL 數據庫表使用localStorage和 ajax 我這樣做了,但我的問題他只給了我最后一行的數據,因為當我點擊保存時,他給了localStorage新值


<!-- my problem : console.log shows me last item - I want to store all my inputs products without losing previous when I click button save -->

<input type="text" id="products">  
<button onclick="myfunction()">save</button>

<script>
  function myfunction() {
    var products = document.getElementbyid("products").value;
    var save_listProducts = localStorage.setItem("data",products);
  }

  var get_listProducts = localStorage.getItem("data");
  console.log(get_listProducts);

</script>

您需要添加更多代碼才能在localStorage中維護“列表”(數組)。 只要數組是字符串,實際上將數組存儲在localStorage中就沒有問題 - 並且要將數組轉換為字符串(並且能夠稍后解析它),您可以使用 JSON.stringify (和 JSON.parse 來獲取回來了)

function addNewItem (item) {
  let myList = JSON.parse(localStorage.getItem("myList", "[]"));
  myList.push(item);
  localStorage.setItem("myList", JSON.stringify(myList));
}

function getAllItems () {
  return JSON.parse(localStorage.getItem("myList", "[]"));
}
function removeItem (index) {
  let myList = JSON.parse(localStorage.getItem("myList", "[]"));
  myList.splice(index, 1);
  localStorage.setItem("myList", JSON.stringify(myList));
}

這只是一個示例,需要修改以適合您的代碼,請不要只是復制/粘貼它

在你的例子中

<input type="text" id="product">  
<button onclick="myfunction()">save</button>

<script>

  function myfunction() {
    var product = document.getElementbyid("product").value;
    addNewItem(product);
    console.log(getAllItems());
  }

  function addNewItem (item) {
    var myList = JSON.parse(localStorage.getItem("myList", "[]"));
    myList.push(item);
    localStorage.setItem("myList", JSON.stringify(myList));
  }

  function getAllItems () {
    return JSON.parse(localStorage.getItem("myList", "[]"));
  }

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM