admin管理员组文章数量:1402024
I'm generating list of dishes(which are objects) and when user clicks button the InitializeFoodList() should add selected item to sessionStorage. Then in RetrieveDataFromCart() I want to loop over the sessionStorage and show all this items in console.
The problem is the end result is that the item property is null or it's just showing the last added item and next one are null.
Anyone knows a better way to achieve this?
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=".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>
I'm generating list of dishes(which are objects) and when user clicks button the InitializeFoodList() should add selected item to sessionStorage. Then in RetrieveDataFromCart() I want to loop over the sessionStorage and show all this items in console.
The problem is the end result is that the item property is null or it's just showing the last added item and next one are null.
Anyone knows a better way to achieve this?
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./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>
Share
Improve this question
asked May 27, 2018 at 17:39
cannelle28cannelle28
3078 silver badges17 bronze badges
2 Answers
Reset to default 4I would just keep whole array in storage under one key
Then you can add/remove or modify objects in array in memory and store modified array every time you change it
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
})
You are using sessionStorage correctly but there are some issues in this snippet . Firstly, while setting item in sessionStorage, you are adding 'cart' as key everytime so it results in overriding the previous value stored as items in sessionStorage are stored as key value pairs and keys should be unique otherwise it updates the previous value stored at the same key.
So I have added value of i with key name 'cart' i.e 'cart' + i . You can use any of unique keys according to your use case . And Secondly instead of getting particular key using localStorage Use session storage (seems to be some typo)
Updated snippet
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);
}
}
本文标签: javascriptHow to retrieve objects from sessionStorageStack Overflow
版权声明:本文标题:javascript - How to retrieve objects from sessionStorage? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744346249a2601777.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论