簡體   English   中英

會話存儲項目購物車

[英]Session storage items cart

我試圖改編我在stackoverflow上找到的代碼,但不幸的是我沒有成功。 我要存儲一個變量,該變量在刷新頁面后將保持不變,直到清除cookie。

在代碼中,當我按下“刷新”后,變量將重置為0。

為什么? 謝謝。

JS:

 <script>
   var WishCounter = 0;
   let localStorage = window.localStorage
   $(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-cart2").click(function(){
              WishCounter++;
              localStorage.setItem('WishCounter', WishCounter);
              $(".cart-wish").text(WishCounter);
              localStorage.getItem('WishCounter');



          });
      });

      </script>

HTML:

<a class="add-to-cart2" role="button" data-toggle="modal">
                <img src="images/popit/wish.png" class="buttons-featured-wish" width="91" height="91" border="0" alt=""></a>

WishCounter始終為0,因為它是在頁面加載時設置的。 這可以通過使用localStorage.getItem();設置WishCounter的值來WishCounter localStorage.getItem(); 如果有價值

例:

<script>
    let localStorage = window.localStorage;
    var WishCounter = localStorage.getItem('WishCounter') === null ? 0 : localStorage.getItem('WishCounter');

    $(".cart-wish").text(WishCounter);

    $(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-cart2").click(function(){
            WishCounter++;
            localStorage.setItem('WishCounter', WishCounter);
            $(".cart-wish").text(WishCounter);

        });
    });

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM