K
K
Knyashshsh2018-02-24 02:46:12
JavaScript
Knyashshsh, 2018-02-24 02:46:12

Why don't the numbers add up?

There is a code that, when clicked, should go through the goods in the basket and calculate their cost

$('.add-item').click(function () {
    var price = $(this).parent().find('.price').text();
    $('.cart-window ul').append($('<div class="item">123 <span>'+price+'</span></div>'));
    var sum = 0; //начальная сумма корзины
    $('.cart-window ul').each(function () { // проходимся по товарам
      var price_item = $(this).find('.item span').text(); //узнаём цену товара
      console.log(typeof(sum)); // для отладки
      console.log(typeof(price_item)); // для отладки
      price_item = parseInt(price_item); //переводим строку в число
      console.log(typeof(price_item)); // для отладки
      sum += price_item; //считываем сумму товаров
      console.log(sum);  // для отладки
    });
    $('.cart-window .amount').text(sum); //выводим сумму заказа
  });

I can’t understand why they don’t add up normally, sum is the number price_item is also distilled into a number,
and the sum is as if after adding the rows
Screen from the console
5a90a6a335fdf659905094.jpeg

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-24
@fyapy

Replace with and replace with . And now, instead of iterating over .items, you process the entire list at once, getting the contents of all .item spans at once - naturally, the lines are glued together. $('.cart-window ul').each$('.cart-window ul .item').each$(this).find('.item span').text()$(this).find('span').text()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question