Проблема в том, что, поскольку новые функции, которые я добавил, используют поля со списком или параметры, каждый раз, когда я добавляю в корзину товары с немного другим сочетанием цвета и материала, если я попытаюсь удалить ранее добавленные комбинации, я смогу удалить только самую новую.
Я чувствую это легче показать в коде, чем пытаться объяснить.
Это моя логика удаления товаров из корзины:
Код: Выделить всё
//removing one particular item completely from the cart
AS_shoppingCart.removeItemAll = function(name, color, material){
//for every item in the array which has the same name; remove.
for (var i in this.cartShop)
if(this.cartShop[i].name === name, this.cartShop[i].color === color, this.cartShop[i].material === material) {
this.cartShop.splice(i, 1);
break;
};
AS_shoppingCart.saveLocalCart();
};
Для тех, кому интересно, вот как я храню экземпляры объектов массив:
Код: Выделить всё
//THE LOGIC FOR THE SHOPPING CART - OOP
var AS_shoppingCart = {};
//cart where the item objects will be stored
AS_shoppingCart.cartShop = [];
//item object and its properties
AS_shoppingCart.Item = function(name, price, quantity, color, material) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.color = color;
this.material = material;
};
Вот как выглядит мой HTML. Обратите внимание: проблема в этих опциях. Чтобы удалить старые записи в корзине, мне нужно выбрать комбинацию опций, аналогичную указанному элементу. Это логически логично, но проблема в том, что я не имею ни малейшего понятия, как обойти эту проблему.
< div class="snippet-code">
Код: Выделить всё
[h4]Customisation:[/h4]
Color
Material
Default
Blue
Green
Brown
Alloy
Steel
Carbon Fibre
Titanium
Add to cart
Это часть jQuery, где используется логика. Примечание; Я вырезал ненужные части из фрагмента.
< pre class="snippet-code-js lang-js Prettyprint-override">
Код: Выделить всё
$(document).ready(function(){
/* CART */
//assigning a click event to DOM object
$(".add-to-cart").click(function(event){
//prevents the page from being refreshed
event.preventDefault();
//sets the name variable to a clicked data-name
var name = $(this).attr("data-name");
//sets the price to the number version of data-price attribute
var price = Number($(this).attr("data-price"));
var color = $('#colors option:selected').data('color');
var material = $('#materials option:selected').data('material');
$(".add-to-cart").attr({
"data-color" : color,
"data-material" : material
});
AS_shoppingCart.addItem(name, price, 1, color, material);
displayCart();
});
$("#show-cart").on("click",".delete-item", function(event){
var name = $(this).attr("data-name");
console.log(name);
AS_shoppingCart.removeItemAll(name);
displayCart();
});
});
Код: Выделить всё
Поэтому мой вопрос заключается в том, как мне убедиться, что я не На самом деле мне не нужно устанавливать параметры товара для более старых товаров в корзине, чтобы удалить их.
РЕДАКТИРОВАНИЕ: показ моей функции addItem:
Код: Выделить всё
//adds items to the cart
AS_shoppingCart.addItem = function(name, price, quantity, color, material){
/*checks to see if the item with the identical name exists in the cart
if so, it will only increment the quantity of the said item (no redundancies)*/
for(let item of this.cartShop) {
if(item.name === name && item.color === color && item.material === material) {
item.quantity += quantity;
this.saveLocalCart();
return;
};
};
var item = new this.Item(name, price, quantity, color, material);
this.cartShop.push(item);
this.saveLocalCart();
};
Подробнее здесь: https://stackoverflow.com/questions/416 ... -correctly