我的 jQuery 代码在第一次点击时不起作用?

my jQuery code not working on the first click?

在第一次点击时,代码没有找到“item.id”。 "items" 来自 LocalStorage,不为 NULL

console.log(items);
$('.user-basket__product-delete>span.icon-trash').click(function(){
            let n = $(this).parents('.user-basket__product').attr('data-id');
           console.log(items);
            $.each(items, function(index,item){
                if(item.id === parseInt(n)){
                    items.splice(index,1);
                    localStorage.setItem('items',JSON.stringify(items)); 
                    $.priceEvents.totalPriceEvent(items);
                }
            })
            $(this).parents('.user-basket__product').remove();
            setTimeout(function() { 
                $.noContent();
            }, 200);
        })

和错误

Uncaught TypeError: Cannot read property 'id' of null
    at all.js:4075
    at Function.each (all.js:169)
    at HTMLSpanElement.<anonymous> (all.js:4074)
    at HTMLSpanElement.dispatch (all.js:1945)
    at HTMLSpanElement.h.handle (all.js:1883)
(anonymous) @ all.js:4075
each @ all.js:169
(anonymous) @ all.js:4074
dispatch @ all.js:1945
h.handle @ all.js:1883

以及单击之前和第一次单击之后控制台中的项目。我现在意识到,代码在第一次单击时删除了 LocalStorage 中的 item.id,但删除了 return 三元素数组。第二次点击后,删除父元素并修复数组

(3) [{…}, {…}, {…}]
0: {id: 5, name: "Product 4", detail: "Lorem ipsum dolor sit amet", price: "99", cargo: "9.95", …}
1: {id: 3, name: "Product 2 Lorem Ipsum mix Pro", detail: "Lorem ipsum dolor sit amet", oldPrice: "110", price: "99", …}
2: {id: 4, name: "Product 3", detail: "Lorem ipsum dolor sit amet", price: "99", cargo: "9.95", …}
length: 3
__proto__: Array(0)
all.js:4074 
(3) [{…}, {…}, {…}]
0: {id: 3, name: "Product 2 Lorem Ipsum mix Pro", detail: "Lorem ipsum dolor sit amet", oldPrice: "110", price: "99", …}
1: {id: 4, name: "Product 3", detail: "Lorem ipsum dolor sit amet", price: "99", cargo: "9.95", …}
length: 2
__proto__: Array(0)

看来 localStorage.setItem() 是不可靠的同步 (see here)。在循环外调用该方法可能是个好主意。此外,为防止出现竞争情况,您可能希望避免在操作完成之前删除正在使用的数据。也许复制数据并从中工作。在下面的示例中,它使用过滤器,因为您似乎正在按 ID 删除项目,但将所有其他信息保存到存储中。

$('.user-basket__product-delete>span.icon-trash')
  .click(function () {
    const n = $(this).parents('.user-basket__product').attr('data-id');
    const updatedItems = items.filter(item => item.id !== parseInt(n));
    items = updatedItems;

    localStorage.setItem('items', JSON.stringify(items));
    $.priceEvents.totalPriceEvent(items);
    $(this).parents('.user-basket__product').remove();

    // Probably safe to do this without a timeout
    setTimeout(function() { 
      $.noContent();
    }, 200);
}