我正在开发购物车。购物车中的产品由本地存储阵列填充
{id: "1280-01-601-0179-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514502694923", name: "NRP CABLE ASSEMBLY", price: "$32", quantity: "33"}
{id: "1660-01-519-2834-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514573672302", name: "SEPARATOR WATER,AIRCRAFT AIR CON", price: "$322", quantity: "1"}
{id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}
这是js代码
var arrayLength = cartarry.length;
for (var i = 0; i < arrayLength; i++) {
var id = cartarry[i].id;
var name = cartarry[i].name;
var price = parseInt(cartarry[i].price.replace('$',""))
var quantity = parseInt(cartarry[i].quantity);
var linetotal = price * quantity;
var itemcontainer = document.getElementById('myContent');
// itemcontainer.innerHTML = '';
//Do something
var itemcard = `
<div class="product" id="${id}">
<div class="product-details">
<div class="product-title">Dingo Dog Bones</div>
<p class="product-description"> ${name}</p>
</div>
<div class="product-price" id='productprice'>${price}</div>
<div class="product-quantity">
<input type="number" id='productquantity' value=${quantity} min="1">
</div>
<div class="product-removal">
<button class="remove-product">
Remove
</button>
</div>
<div class="product-line-price" id='productlineprice' >${linetotal}</div>
</div>
`
;
itemcontainer.innerHTML += itemcard;
calculatelinetotal()
}
我想在数量变化时重新计算购物车总价。因此,在数量变化时更新本地存储阵列,然后重新计算以获得更新的价格和最终成本。 我能够通过此
获取更改数量父项的ID$('.product-quantity input').change( function() {
var id = $(this).parents('.product')[0].id;
});
这是
的一个例子 console.log(id) // 1280-01-601-0179-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514502694923"
如何更新特定ID的本地存储阵列数量并删除特定ID的数组?
答案 0 :(得分:1)
在本地存储中,您只能存储字符串。所以最简单的方法是使用JSON.stringify
和JSON.parse
来存储json编码的对象/数组。只需完全重写该项目。
基本上:
function updateArray (key, index, value) {
var array = JSON.parse(localStorage.getItem(key));
array[idx] = value;
localStorage.setItem(key, JSON.stringify(array));
}