Javascript передал саму строку вместо длины индекса, что не так с моим кодом?
Я пытаюсь передать id элемента и индекс id элемента при нажатии на кнопку. Но код выдает разные результаты. Для справки, я приложил ожидаемый результат и полученный результат. Любая помощь будет высоко оценена
if(localStorage.getItem('cart')==null){
var cart={};
}
else{
cart = JSON.parse(localStorage.getItem('cart'));
}
$(document).on('click','.btn-cart',function(c){
c.preventDefault();
console.log("Add to Cart Button clicked");
var item_id = this.id.toString();
console.log(item_id);
if(cart[item_id]!=undefined){
cart[item_id] =cart[item_id] + 1
}
else{
cart[item_id]= 1
}
console.log(cart);
localStorage.setItem('cart',JSON.stringify(cart));
console.log(Object.keys(cart).length);
});
Я ожидаю этого:
Но произошло следующее:
Мой HTML:
<div id="alignment" class="grid-only-content product-action-horizontal">
<a href="{{url}}" id="{{product.id}}" class="btn-product-icon btn-cart icon-cart" title="Add to Cart">
</a>
</div>