我有一个代码,可以在本地存储中添加、显示和删除对象及其工作,但是每当我试图更新特定对象时,它就会覆盖所有东西,而不是仅仅更改我想要的特定对象。
我的代码
$(".qty-val-ls").on("change", function() {
let record = localStorage.getItem("guestCart");
let index = $(this).attr("id");
if(record == null)
{
recordObj = [];
}else{
recordObj = JSON.parse(record);
}
recordObj[index].price = $(this).val() * parseInt(recordObj[index].price);
localStorage.setItem('guestCart', recordObj[index].price);
})我的输入
<input type="number" class="qty-val-ls" min="1" id="${index}" value="4000" onChange="">这里的${index}是本地存储中的id,jquery中的索引是对象在本地存储中的位置,它从0、1、2等开始。
MY数组(LOCALSTORAGE中的对象)
[{"id":"11","name":"Rts 512GB USB Flash Drive Pendrive Memory USB 3.0","price":"3000","img":"newusb.png","qty":1},
{"id":"10","name":"MP3 Music Player Audio Player -Black","price":"5000","img":"mp3.png","qty":1},
{"id":"5","name":"Blue Louis Vuitton Women Bag","price":"10000","img":"newbag.png","qty":1},
{"id":"1","name":"Samsung Galaxy S9 6gb ram, 32gb rom, 16mpbs","price":"100000","img":"newphone.png","qty":1}]因此,请您在计算后如何更改该值,并将其放回它应该在的位置。
编辑:我已经检查过其他类似的关于堆栈溢出的问题,但是似乎没有一个有效。
发布于 2020-07-14 20:07:34
我将试图解释在评论中也说了什么,并给出了一个好的方法。首先,您在localStorage中使用recordObj[index].price而不是完整的recordObj覆盖存储的对象。但是,正如您已经说过的,存储recordObj然后获取它的值会给出"[object Object]",因为它被解析为字符串。考虑到我说过在访问items属性时要小心,因为它还不存在,这段代码应该适用于您:
$('.qty-val-ls').on('change', function onChange() {
const record = localStorage.getItem('guestCart');
const recordObj = record ? JSON.parse(record) : [];
const index = $(this).attr('id');
if (recordObj[index]) {
recordObj[index].price = $(this).val() * parseInt(recordObj[index].price, 10);
}
localStorage.setItem('guestCart', JSON.stringify(recordObj));
});更详细地解释我所做的事情:
JSON.parse一起解析,因为它是字符串化的;如果不存在,则将其初始化为空数组。如果在给定的索引上存在项目,则根据需要设置价格。我还向(https://eslint.org/docs/rules/radix)https://stackoverflow.com/questions/62901886
复制相似问题