카트에서 항목을 올바르게 제거 할 수 없음 (JavaScript 및 Jquery)

보컬 로이드

기본적으로 제품 사용자 정의를 지원하기 위해 최근에 업그레이드 한 카트가 있습니다 (매우 기본적인 수준에서). 업그레이드에는 이름, 가격 및 수량 외에도 특정 자전거의 색상 및 재료 유형이 포함되었습니다.

문제는 내가 추가 한 새로운 기능이 콤보 박스 나 옵션을 사용하기 때문에 이전에 추가 한 조합을 삭제하려고하면 약간 다른 색상과 재료 조합으로 장바구니에 항목을 추가 할 때마다 삭제 만 허용된다는 것입니다. 최신 것.

나는 이것을 시도하고 설명하는 것보다 코드로 보여주는 것이 더 쉽다고 생각합니다. 이것은 장바구니에서 항목을 삭제하는 논리입니다.

//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>
                    <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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Localstorage에서 항목을 삭제할 수 없음-JavaScript

분류에서Dev

Chidren 카운트 반환 항상 0, 올바르게 도달 할 수 없음

분류에서Dev

제거 할 수 있습니까? "Index : [], Empty DataFrame"및 올바르게 읽음

분류에서Dev

배열에서 항목을 제거 할 수 없음 Vuex

분류에서Dev

장바구니 Android Studio에서 항목을 제거 할 수 없습니다.

분류에서Dev

Javascript에서 XML을 올바르게 읽을 수 없습니다.

분류에서Dev

Python 2.7-이메일 제목 헤더 줄을 올바르게 디코딩 할 수 없음

분류에서Dev

jQuery 정렬 가능 목록 2.0에서 새로 추가 된 항목을 제거 할 수 없습니다.

분류에서Dev

재귀 코드에서 올바르게 중단 할 수 없음

분류에서Dev

R XTS 패키지 to.minutes – 5m에서 15m 및 30m 시계열을 올바르게 생성 할 수 없음

분류에서Dev

mongoose : 배열에서 항목을 제거 할 수 없습니다.

분류에서Dev

lsitviewbox에서 항목을 제거 할 수 없습니다.

분류에서Dev

출력을 올바르게 정렬 할 수 없음

분류에서Dev

WebView, html을 올바르게로드 할 수 없음

분류에서Dev

BREW 공식을 올바르게 설치할 수 없습니다 (/ usr / local / lib에서 권한이 거부 됨)

분류에서Dev

nest 및 elasticsearch로 많은 항목을 인덱싱-어떤 노드에서도 게시를 수행 할 수 없음

분류에서Dev

jQuery가 개별 버튼을 사용하여 별도의 div를 올바르게 슬라이드 할 수 없음

분류에서Dev

부울 인덱싱 (Pandas)을 사용할 때 새 열에 값을 올바르게 할당 할 수 없음

분류에서Dev

jQuery를 사용하여 복잡한 json 객체에 올바르게 액세스 할 수 없음

분류에서Dev

SQL 조인-데카르트 결과를 제거 할 수 없음

분류에서Dev

자바 스크립트의 할일 목록-작업을 삭제 한 후 다른 작업을 올바르게 선택할 수 없습니다.

분류에서Dev

Thunar가 파티션을 올바르게 마운트 / 마운트 해제 할 수 없습니다.

분류에서Dev

html에서지도를 올바르게로드 할 수 없음을 보여주는 Google지도

분류에서Dev

날짜 '0001-01-01'을 Java에서 C #으로 올바르게 변환 할 수 없음

분류에서Dev

목록에서 '특정'빈 항목을 제거 할 수 없습니다.

분류에서Dev

HTML 및 값을 jQuery Datatables 1.10으로 복제 할 수 없음

분류에서Dev

Android Studio에서 파일 내용을 올바르게로드 할 수 있음

분류에서Dev

PHP에서 zip 아카이브를 만들 수 있지만 올바르게 다운로드 할 수 없음 2

분류에서Dev

React에서 테이블을 올바르게 렌더링 할 수 없습니다.

Related 관련 기사

  1. 1

    Localstorage에서 항목을 삭제할 수 없음-JavaScript

  2. 2

    Chidren 카운트 반환 항상 0, 올바르게 도달 할 수 없음

  3. 3

    제거 할 수 있습니까? "Index : [], Empty DataFrame"및 올바르게 읽음

  4. 4

    배열에서 항목을 제거 할 수 없음 Vuex

  5. 5

    장바구니 Android Studio에서 항목을 제거 할 수 없습니다.

  6. 6

    Javascript에서 XML을 올바르게 읽을 수 없습니다.

  7. 7

    Python 2.7-이메일 제목 헤더 줄을 올바르게 디코딩 할 수 없음

  8. 8

    jQuery 정렬 가능 목록 2.0에서 새로 추가 된 항목을 제거 할 수 없습니다.

  9. 9

    재귀 코드에서 올바르게 중단 할 수 없음

  10. 10

    R XTS 패키지 to.minutes – 5m에서 15m 및 30m 시계열을 올바르게 생성 할 수 없음

  11. 11

    mongoose : 배열에서 항목을 제거 할 수 없습니다.

  12. 12

    lsitviewbox에서 항목을 제거 할 수 없습니다.

  13. 13

    출력을 올바르게 정렬 할 수 없음

  14. 14

    WebView, html을 올바르게로드 할 수 없음

  15. 15

    BREW 공식을 올바르게 설치할 수 없습니다 (/ usr / local / lib에서 권한이 거부 됨)

  16. 16

    nest 및 elasticsearch로 많은 항목을 인덱싱-어떤 노드에서도 게시를 수행 할 수 없음

  17. 17

    jQuery가 개별 버튼을 사용하여 별도의 div를 올바르게 슬라이드 할 수 없음

  18. 18

    부울 인덱싱 (Pandas)을 사용할 때 새 열에 값을 올바르게 할당 할 수 없음

  19. 19

    jQuery를 사용하여 복잡한 json 객체에 올바르게 액세스 할 수 없음

  20. 20

    SQL 조인-데카르트 결과를 제거 할 수 없음

  21. 21

    자바 스크립트의 할일 목록-작업을 삭제 한 후 다른 작업을 올바르게 선택할 수 없습니다.

  22. 22

    Thunar가 파티션을 올바르게 마운트 / 마운트 해제 할 수 없습니다.

  23. 23

    html에서지도를 올바르게로드 할 수 없음을 보여주는 Google지도

  24. 24

    날짜 '0001-01-01'을 Java에서 C #으로 올바르게 변환 할 수 없음

  25. 25

    목록에서 '특정'빈 항목을 제거 할 수 없습니다.

  26. 26

    HTML 및 값을 jQuery Datatables 1.10으로 복제 할 수 없음

  27. 27

    Android Studio에서 파일 내용을 올바르게로드 할 수 있음

  28. 28

    PHP에서 zip 아카이브를 만들 수 있지만 올바르게 다운로드 할 수 없음 2

  29. 29

    React에서 테이블을 올바르게 렌더링 할 수 없습니다.

뜨겁다태그

보관