如何从sessionStorage中检索对象?

时间:2018-05-27 17:39:34

标签: javascript jquery html session-storage

我正在生成菜肴列表(对象),当用户点击按钮时,InitializeFoodList()应该将所选项目添加到sessionStorage。然后在RetrieveDataFromCart()中,我想遍历sessionStorage并在控制台中显示所有这些项目。

问题是最终结果是item属性为null或者它只是显示最后添加的项目而下一个是null。

任何人都知道更好的方法来实现这一目标吗?

var list = [{
    id: 1,
    name: "Spaghetti",
    price: 15,
    category: "main",
    pictureSrc: "images/food/spaghetti.jpg"
  },
  {
    id: 2,
    name: "Lasagne",
    price: 20,
    category: "main",
    pictureSrc: "images/food/Lasagne.jpg"
  },
  {
    id: 3,
    name: "Coca-cola",
    price: 5,
    category: "drinks",
    pictureSrc: "images/food/cola.jpg"
  },
  {
    id: 4,
    name: "Chicken",
    price: 12,
    category: "main",
    pictureSrc: "images/food/chicken.jpg"
  },
];

function InitializeFoodList() {

  var foodList = $('#foodList');

  for (let i = 0; i < list.length; i++) {
    const element = list[i];
    var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>';
    foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>");
    $('#add' + i).click(function() {
      sessionStorage.setItem("cart", JSON.stringify(element));
    });
  }
}

function RetrieveDataFromCart() {

  var elements = [];

  for (let i = 0; i < sessionStorage.length; i++) {
    var element = JSON.parse(sessionStorage.getItem(localStorage.key(i)));
    elements.push(element);
    console.log(element.name);
  }

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button onclick="InitializeFoodList()">Click me</button>
  <button onclick="RetrieveDataFromCart()">Retrieve</button>
  <ul id="foodList" class="list-inline"></ul>
</div>

2 个答案:

答案 0 :(得分:1)

我只是将整个数组保存在一个键下

然后,您可以在内存中添加/删除或修改数组中的对象,并在每次更改时存储已修改的数组

function getStoredCart(){
    // return stored array and if not existing return an empty array
    return JSON.parse(sessionStorage.getItem('cart') || '[]')
}

function saveCart(array){
   sessionStorage.setItem("cart", JSON.stringify(array)); 
}

// example deleting item
function deleteItem(item){
    var itemIndex = cartList.indexOf(item)
    cartArray.splice(itemIndex,1); // remove from stored array       
    saveCart(cartArray ); // save it back into storage
}

// example adding item
function addItem(itemObject){       
    cartArray .push(itemObject); // push new object to array       
    saveCart(cartArray ); // save it back into storage
}


// keep array reference in variable whole time page is active
var cartArray = getStoredCart();

$.each(cartArray , function(i, item){
    // add the html for each item and use `item` reference in click handlers when doing modifications
})

答案 1 :(得分:0)

您正在使用sessionStorage,但此代码段中存在一些问题。首先,在sessionStorage中设置项目时,每次都会添加“cart”作为键,因此它会覆盖存储的先前值,因为sessionStorage中的项目存储为键值对,键应该是唯一的,否则它会更新存储在同样的关键。

所以我增加了i的值,键名为'cart',即'cart'+ i。您可以根据用例使用任何唯一键。 其次,而不是使用localStorage使用会话存储获取特定密钥(似乎是一些错字)

更新了代码段

var list = [{
    id: 1,
    name: "Spaghetti",
    price: 15,
    category: "main",
    pictureSrc: "images/food/spaghetti.jpg"
},
{
    id: 2,
    name: "Lasagne",
    price: 20,
    category: "main",
    pictureSrc: "images/food/Lasagne.jpg"
},
{
    id: 3,
    name: "Coca-cola",
    price: 5,
    category: "drinks",
    pictureSrc: "images/food/cola.jpg"
},
{
    id: 4,
    name: "Chicken",
    price: 12,
    category: "main",
    pictureSrc: "images/food/chicken.jpg"
},
];

function InitializeFoodList() {

var foodList = $('#foodList');

for (let i = 0; i < list.length; i++) {
    const element = list[i];
    var buttonText = '<button class="btn btn-primary add" id="add' + i + '">+</button><button class="btn btn-primary" name="remove">-</button>';
    foodList.append("<li class='list-inline-item'><h4>" + element.name + "</h4><p>" + element.price + " zł</p><img alt=''height='200' width='200' class='img-thumbnail' src='" + element.pictureSrc + "'><br>" + buttonText + "</li>");
    $('#add' + i).click(function() {
    sessionStorage.setItem("cart" + i, JSON.stringify(element));
    });
}
}

function RetrieveDataFromCart() {

var elements = [];

for (let i = 0; i < sessionStorage.length; i++) {
    var element = JSON.parse(sessionStorage.getItem(sessionStorage.key(i)));
    elements.push(element);
    console.log(element.name);
}

}