기본적으로 제품 사용자 정의를 지원하기 위해 최근에 업그레이드 한 카트가 있습니다 (매우 기본적인 수준에서). 업그레이드에는 이름, 가격 및 수량 외에도 특정 자전거의 색상 및 재료 유형이 포함되었습니다.
문제는 내가 추가 한 새로운 기능이 콤보 박스 나 옵션을 사용하기 때문에 이전에 추가 한 조합을 삭제하려고하면 약간 다른 색상과 재료 조합으로 장바구니에 항목을 추가 할 때마다 삭제 만 허용된다는 것입니다. 최신 것.
나는 이것을 시도하고 설명하는 것보다 코드로 보여주는 것이 더 쉽다고 생각합니다. 이것은 장바구니에서 항목을 삭제하는 논리입니다.
//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;
};
<div>
<h4>Customisation:</h4>
<table>
<tr>
<th>Color</th>
<th>Material</th>
</tr>
<tr>
<td>
<select id="colors" name="colors">
<option data-color="Default">Default</option>
<option data-color="Blue">Blue</option>
<option data-color="Green">Green</option>
<option data-color="Brown">Brown</option>
</select>
</td>
<td>
<select id="materials" name="materials">
<option data-material="Alloy">Alloy</option>
<option data-material="Steel">Steel</option>
<option data-material="Carbon Fibre">Carbon Fibre</option>
<option data-material="Titanium">Titanium</option>
</select>
</td>
</tr>
</table>
</div>
<div class="button-group">
<button class="add-to-cart" data-name="Aluminum road bike " data-price="256">Add to cart</button>
</div>
이것은 로직을 사용하는 jQuery 부분입니다. 노트; 스 니펫에서 관련없는 부분을 잘라 냈습니다.
$(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();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
그래서 제 질문은 제가 실제로 제품 아이템 옵션을 삭제하기 위해 카트에있는 이전 아이템으로 설정하지 않아도되도록 어떻게해야하는지입니다.
감사합니다.
편집 : 내 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();
};
break
장바구니에서 첫 번째 항목을 찾은 후 사용하기 때문에 발생합니다 . 항목을 먼저 찾은 후 항목을 계속 반복하려면 제거하십시오.
업데이트 2
또한 splice는 항목 수의 변경을 제공하므로 루프를 되돌리고 마지막에서 처음으로 항목을 삭제하거나 다음과 같은 필터 를 사용하는 것이 좋습니다 .
//now items store shopcart with all items except those you want to remove
//so you can store it back to this.cartShop or pass to another method to save new version of shopcart which is more acceptable way
let items = this.cartShop.filter(function(item) => {
return (item.name !== name &&
item.color !== color &&
item.material !== material)
}
따라서 최종 코드는 다음과 같습니다.
AS_shoppingCart.removeItemAll = function(name, color, material){
this.cartShop = this.cartShop.filter(function(item){ return !(item.name === name && item.color === color && item.material === material) });
AS_shoppingCart.saveLocalCart();
};
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다