Отображение количества продуктов в значке сверху этого продукта с использованием javascript или jquery?

Отображение количества продуктов в значке сверху этого продукта с использованием javascript или jquery?

Как получить счет для любого товара в корзине, который будет отображаться на странице товара в значке сверху этого товара с использованием javascript или jquery? Я попытался проверить, равны ли товары в корзине значению атрибута данных, чтобы он мог определить, какой товар находится в основной корзине, и показать значок подсчета, но в итоге все остальные элементы в цикле зацикливались. корзина в продуктах это количество не принадлежит …

Код

  var shoppingCart = (function() { cart = []; // Constructor function Item(name, price, count) { this.name = name; this.price = price; this.count = count; } // Save cart function saveCart() { sessionStorage.setItem('shoppingCart', JSON.stringify(cart)); } // Load cart function loadCart() { cart = JSON.parse(sessionStorage.getItem('shoppingCart')); } if (sessionStorage.getItem("shoppingCart") != null) { loadCart(); } var obj = {}; // Add to cart obj.addItemToCart = function(name, price, count) { for(var item in cart) { if(cart[item].name === name) { cart[item].count   ; saveCart(); return; } } var item = new Item(name, price, count); cart.push(item); saveCart(); } // Set count from item obj.setCountForItem = function(name, count) { for(var i in cart) { if (cart[i].name === name) { cart[i].count = count; break; } } }; // Remove item from cart obj.removeItemFromCart = function(name) { for(var item in cart) { if(cart[item].name === name) { cart[item].count --; if(cart[item].count === 0) { cart.splice(item, 1); } break; } } saveCart(); } // Remove all items from cart obj.removeItemFromCartAll = function(name) { for(var item in cart) { if(cart[item].name === name) { cart.splice(item, 1); break; } } saveCart(); } // Clear cart obj.clearCart = function() { cart = []; saveCart(); } // Count cart obj.totalCount = function() { var cartArray = shoppingCart.listCart(); var totalCount = cartArray.length; return totalCount; } // Total cart obj.totalCart = function() { var totalCart = 0; for(var item in cart) { totalCart  = cart[item].price * cart[item].count; } return Number(totalCart.toFixed(2)); } // List cart obj.listCart = function() { var cartCopy = []; for(i in cart) { item = cart[i]; itemCopy = {}; for(p in item) { itemCopy[p] = item[p]; } itemCopy.total = Number(item.price * item.count).toFixed(2); cartCopy.push(itemCopy) } return cartCopy; } return obj; })(); // Add item $('.add-to-cart').click(function(event) { event.preventDefault(); var name = $(this).data('name'); var price = Number($(this).data('price')); shoppingCart.addItemToCart(name, price, 1); displayCart(); iconCart(); }); // Clear items $('.clear-cart').click(function() { shoppingCart.clearCart(); displayCart(); iconCart(); }); // This function displays the cart function displayCart() { var cartArray = shoppingCart.listCart(); var output = ""; for(var i in cartArray) { output  = "{amp}lt;tr{amp}gt;"   "{amp}lt;td{amp}gt;"   cartArray[i].name   "{amp}lt;/td{amp}gt;"   "{amp}lt;td{amp}gt;("   cartArray[i].price   "){amp}lt;/td{amp}gt;"   "{amp}lt;td{amp}gt;{amp}lt;div class='input-group'{amp}gt;{amp}lt;button class='minus-item input-group-addon btn btn-primary' data-name="   cartArray[i].name   "{amp}gt;-{amp}lt;/button{amp}gt;"   "{amp}lt;input type='number' class='item-count form-control' data-name='"   cartArray[i].name   "' value='"   cartArray[i].count   "'{amp}gt;"   "{amp}lt;button class='plus-item btn btn-primary input-group-addon' data-name="   cartArray[i].name   "{amp}gt; {amp}lt;/button{amp}gt;{amp}lt;/div{amp}gt;{amp}lt;/td{amp}gt;"   "{amp}lt;td{amp}gt;{amp}lt;button class='delete-item btn btn-danger' data-name="   cartArray[i].name   "{amp}gt;X{amp}lt;/button{amp}gt;{amp}lt;/td{amp}gt;"   " = "   "{amp}lt;td{amp}gt;"   cartArray[i].total   "{amp}lt;/td{amp}gt;"   "{amp}lt;/tr{amp}gt;"; } $('.show-cart').html(output); $('.total-cart').html(shoppingCart.totalCart()); $('.total-count').html(shoppingCart.totalCount()); } // This is the function responsible for creating the badge function iconCart() { var cartArray = shoppingCart.listCart(); var arrayName = []; var output = ""; for(var a in cartArray) { output  = "{amp}lt;badge class='badge-danger'{amp}gt;"  cartArray[a].count  "{amp}lt;/badge{amp}gt;" if ($('.add-to-cart[data-name="'   cartArray[a].name   '" ]')) { $('.add-to-cart[data-name="'   cartArray[a].name   '" ]').html(output); } } } // Delete item button $('.show-cart').on("click", ".delete-item", function(event) { var name = $(this).data('name') shoppingCart.removeItemFromCartAll(name); displayCart(); iconCart(); }) // -1 $('.show-cart').on("click", ".minus-item", function(event) { var name = $(this).data('name') shoppingCart.removeItemFromCart(name); displayCart(); iconCart(); }) //  1 $('.show-cart').on("click", ".plus-item", function(event) { var name = $(this).data('name') shoppingCart.addItemToCart(name); displayCart(); iconCart(); }) // Item count input $('.show-cart').on("change", ".item-count", function(event) { var name = $(this).data('name'); var count = Number($(this).val()); shoppingCart.setCountForItem(name, count); displayCart(); iconCart(); }); displayCart(); iconCart(); 
 {amp}lt;body{amp}gt; {amp}lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"{amp}gt;{amp}lt;/script{amp}gt; {amp}lt;!-- Main --{amp}gt; {amp}lt;div class="container"{amp}gt; {amp}lt;div class="row"{amp}gt; {amp}lt;div class="col"{amp}gt; {amp}lt;div class="card" style="width: 20rem;"{amp}gt; {amp}lt;img class="card-img-top" src="https://www.azspagirls.com/files/2010/09/orange.jpg" alt="Card image cap"{amp}gt; {amp}lt;div class="card-block"{amp}gt; {amp}lt;h4 class="card-title"{amp}gt;Orange{amp}lt;/h4{amp}gt; {amp}lt;p class="card-text"{amp}gt;Price: $0.5{amp}lt;/p{amp}gt; {amp}lt;button data-name="Orange" data-price="0.5" class="add-to-cart btn btn-primary"{amp}gt;Add to cart{amp}lt;/button{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="col"{amp}gt; {amp}lt;div class="card" style="width: 20rem;"{amp}gt; {amp}lt;img class="card-img-top" src="https://images.all-free-download.com/images/graphicthumb/vector_illustration_of_ripe_bananas_567893.jpg" alt="Card image cap"{amp}gt; {amp}lt;div class="card-block"{amp}gt; {amp}lt;h4 class="card-title"{amp}gt;Banana{amp}lt;/h4{amp}gt; {amp}lt;p class="card-text"{amp}gt;Price: $1.22{amp}lt;/p{amp}gt; {amp}lt;button data-name="Banana" data-price="1.22" class="add-to-cart btn btn-primary"{amp}gt;Add to cart{amp}lt;/button{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="col"{amp}gt; {amp}lt;div class="card" style="width: 20rem;"{amp}gt; {amp}lt;img class="card-img-top" src="https://3.imimg.com/data3/IC/JO/MY-9839190/organic-lemon-250x250.jpg" alt="Card image cap"{amp}gt; {amp}lt;div class="card-block"{amp}gt; {amp}lt;h4 class="card-title"{amp}gt;Lemon{amp}lt;/h4{amp}gt; {amp}lt;p class="card-text"{amp}gt;Price: $5{amp}lt;/p{amp}gt; {amp}lt;a href="#" data-name="Lemon" data-price="5" class="add-to-cart btn btn-primary"{amp}gt;Add to cart{amp}lt;/a{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;!-- Modal --{amp}gt; {amp}lt;div class="modal fade" id="cart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"{amp}gt; {amp}lt;div class="modal-dialog modal-lg" role="document"{amp}gt; {amp}lt;div class="modal-content"{amp}gt; {amp}lt;div class="modal-header"{amp}gt; {amp}lt;h5 class="modal-title" id="exampleModalLabel"{amp}gt;Cart{amp}lt;/h5{amp}gt; {amp}lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"{amp}gt; {amp}lt;span aria-hidden="true"{amp}gt;{amp}amp;times;{amp}lt;/span{amp}gt; {amp}lt;/button{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="modal-body"{amp}gt; {amp}lt;table class="show-cart table"{amp}gt; {amp}lt;/table{amp}gt; {amp}lt;div{amp}gt;Total price: ${amp}lt;span class="total-cart"{amp}gt;{amp}lt;/span{amp}gt;{amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;div class="modal-footer"{amp}gt; {amp}lt;button type="button" class="btn btn-secondary" data-dismiss="modal"{amp}gt;Close{amp}lt;/button{amp}gt; {amp}lt;button type="button" class="btn btn-primary"{amp}gt;Order now{amp}lt;/button{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/div{amp}gt; {amp}lt;/body{amp}gt; 

Выход

Выход

Понравилась статья? Поделиться с друзьями:
JavaScript & TypeScript
Adblock
detector