简体   繁体   中英

Shopping Cart with localstorage - how to remove product

I made shoppping cart. I am using localstorage. But i have problem with removing products, what is bad ?

function showElems(){
    $(".cart1").html("<ul class='cartx'></ul>")
    for (var i = 0; i < localStorage.length; i++)   {
        $(".cartx").append("<li class='" +localStorage.key(i) + "' '>" + localStorage.key(i) + "x" + localStorage.getItem(localStorage.key(i)) + 
            "<button class='removeitem' data-remove='" + localStorage.key(i) + "'>REMOVE</button></li>");
    };
};

showElems();

$(".add").click(function(){
    var product = $(this).attr("data-name");
    localStorage.setItem( product, 1 ); // dodanie jednej sztuki do koszyka
    showElems();
});

/* NOT WORKING */

$(".removeitem").click(function(){
    var productremove = $(this).attr("data-remove");
    localStorage['kubek'] = null;
});

http://codepen.io/dominikx96/pen/rLgjrA

There are several parts of the cart that need a little tweaking. Ultimately though, you're on the right track.

I've cleaned up the code a bit and posted the results down below along with a live working example on jsfiddle.net . An explanation follows the code example to explain the changes:

<!-- CART -->
<section id="cart">
  <div class="container">
    <div class="cart1"></div>
  </div>
</section>
<!-- CATEGORY -->
<section id="koszulki" class="category">
    <div class="container">
        <h1 class="category-title">KOSZULKI</h1>
        <div class="category-content">
            <div class="category-item">
                <button class="add" data-name="piersiowka">Dodaj do koszyka</button>
                <button class="more">Zobacz opis</button>
            </div>
            <div class="category-item">
                <button class="add" data-name="szalik">Dodaj do koszyka</button>
                <button class="more">Zobacz opis</button>
            </div>
            <div class="category-item">
                <button class="add" data-name="kubek">Dodaj do koszyka</button>
                <button class="more">Zobacz opis</button>         
            </div>
        </div>
    </div>
</section>
function showElems() {
    var $ul = $('<ul />', { "class": "cartx" });
      for (var a = 0, len = localStorage.length; a < len; a++)   {
        var $li = $('<li />', { "class": localStorage.key(a), text: localStorage.key(a) + "x" + localStorage.getItem(localStorage.key(a)) });
        $('<button />', { "class": "removeitem", data: { remove: localStorage.key(a) }, text: "REMOVE" })
          .appendTo($li);
        $li.appendTo($ul);
      }
    $ul.appendTo($('.cart1').empty());
};

showElems();

$("#koszulki").on('click', '.add', function() {
    if(!localStorage.getItem($(this).data('name'))) {
          localStorage.setItem($(this).data('name'), 1 );
          showElems();
    }
});

$("#cart").on('click', '.removeitem', function() {
    localStorage.removeItem($(this).data('remove'));
    showElems();
});

DEMO: https://jsfiddle.net/5jmmzgkh/2/

The first change that was made was in the showElems() function. The unordered list is now being created in memory and then appended to the .cart1 element. This change is meant to reduce the number of CSS reflows that happen by preventing the browser from redrawing the UI after each list element is appended. It's a subtle change and you won't notice a difference in the three items that are appended. However, if the list were to grow to a few thousand items, the performance gain would become apparent.

The second change that is the delegation of both click events for .add and .removeitem . Not only is the delegation of these events more performant, but it is also required with the .removeitem elements since those elements are not on the screen when the event handler is created. Without delegation here, this handler would not work which is what I would guess is your problem as you note that that handler is not working in your question.

Third, I tweaked your click handler for the .add elements to prevent adding of the same element to your cart. Depending on your use case, you may want to increment the quantity as oppose to only allow the user to add one of each item to the cart. In this case, you'll want to see if the item is already in the user's cart and: if so, increment the quantity value, or if not add the item to the cart.

Finally, I updated the .removeitem function to not only remove the item from the user's cart but to also update the cart UI so that the element disappears from the cart display.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM