Javascript如何更新购物车号码

问题描述 投票:0回答:1

嗨,大家好我决定尝试建立一个电子商务网站,而不是使用Shopify,这样我就可以获得一些经验,但是我想要获得它,以便当用户点击“添加到购物车”时购物车数量更新但我似乎无法让它工作

HTML:

<a class="shopping-cart" href="#"><i class="fa fa-shopping-cart"></i> <span class="cart-badge">1</span></a>
<button class="addcart btn btn-danger add-to-cart" type="button">Add to cart</button>

使用Javascript:

   $(document).ready(function(){
       $(".accordion-heading").click(function(){  
             if($(".accordion-body").is(':visible')){  /* check the condition accordion-body is visible or not */
                 $(".accordion-body").slideUp(200);  /*if content is visible then close accordion-body with specific time duration */
               $(".plusminus").text('+')    /* add plus sign */
           }
           else{
               $(this).next(".accordion-body").slideDown(200); /*if content not visible then 
                                                                                                           show the accordion-body */
               $(this).children(".plusminus").text('-');  /* add minus sign */
           }
       });
   });

我试着用这个例子来帮助我:Link所以我只是想要它然后用户点击“添加到购物车”它将更新我已经建立的计数器

但是javascript并不是我最强的技能,所以任何帮助都会很棒,谢谢

javascript jquery html
1个回答
1
投票

我添加了变量来跟踪购物车中有多少件商品。每次单击“添加到购物车”按钮变量都会+1并更改显示的文本范围。

var currentItems = 0;
$(document).ready(function(){
       $(".accordion-heading").click(function(){  
             if($(".accordion-body").is(':visible')){  /* check the condition accordion-body is visible or not */
                 $(".accordion-body").slideUp(200);  /*if content is visible then close accordion-body with specific time duration */
               $(".plusminus").text('+')    /* add plus sign */
           }
           else{
               $(this).next(".accordion-body").slideDown(200); /*if content not visible then 
                                                                                                           show the accordion-body */
               $(this).children(".plusminus").text('-');  /* add minus sign */
           }
       });
       $(".add-to-cart").click(function(){
           currentItems++;
           $(".cart-badge").text(currentItems);
       });
   });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="shopping-cart" href="#"><i class="fa fa-shopping-cart"></i> <span class="cart-badge">0</span></a>
<button class="addcart btn btn-danger add-to-cart" type="button">Add to cart</button>
© www.soinside.com 2019 - 2024. All rights reserved.