Почему перезаписываются данные только первого элемента?
Всем привет. Есть магазин с товарными секциями - пример в коде. При добавлении товара в корзину происходит пересчет количества товара и его суммы. Для одного товара все считает хорошо, но как только добавляю второй со своими данными - корзина перезаписывает данные только первого, т.е. в итоговой сумме получается цена одного первого продукта, несмотря на то, что в корзине их больше. Вопрос по сохранению данных корзины и их последующему извлечению. Сохраняю данные в массиве, прохожусь по всем элементам с помощью each но что-то не получается правильно перезаписать.. Условие
if ($(this).find('a').attr('href') == product_name) {..}
как я понял срабатывает для всех товаров в корзине или я не прав?
$('.add_to_cart_button').click(function() {
var number = $(this).parents('.product-frame ').find(".input-text.qty.text").val();
var product_name = $(this).parents('.product-frame ').find('.product-section h3 a').attr('href');
$('body').bind('added_to_cart', function() {
var arr = [];
$('#shopping-button .cart_list li').each(function(i) {
arr[i] = $(this).find("span.quantity").text().match(/\d+(?:\.\d+)?/g);
if ($(this).find('a').attr('href') == product_name) {
var html = $(this).find("span.quantity").html();
html = html.replace(/\d+/, number);
$(this).find("span.quantity").html(html);
var quantity = $(this).find("span.quantity").text().match(/\d+(?:\.\d+)?/g);
var basePrice = "";
for (var i = 1; i < quantity.length; i++) {
basePrice += quantity[i];
}
$(this).parents('#shopping-button').find(".shopping-button .amount").text((basePrice * number) + " руб.");
}
});
console.log(arr);
});
});
<!-- Добавление товара в корзину -->
<div class="product-frame ">
<div class="content-description">
<div class="product-section">
<h3><a href="#">Товар 1</a></h3>
<table class="description-table">
<tbody>
<tr>
<td class="product-quantity">
<div class="quantity buttons_added">
<input type="number" step="1" min="1" max="27" id="num_count" name="quantity" value="1" title="Кол." class="input-text qty text" size="4">
<input type="button" value="+1" id="button_plus" class="plus">
<input type="button" value="-1" id="button_minus" class="minus">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="process-section">
<div class="price"><span class="amount" baseprice="360000">1.080.000 руб.</span>
</div>
<a href="#" rel="nofollow" data-product_id="3295" data-quantity="1" class="button add_to_cart_button">Купить</a>
</div>
</div>
<!-- Сама корзина -->
<li id="shopping-button">
<a class="shopping-button" href="#">
<b><span class="amount">360.000 руб.</span></b>
</a>
<ul class="cart_list ">
<li>
<a href="#">
<img width="60" height="60" src="#" class="attachment-60x60 wp-post-image" alt="item-1">
</a>
<div class="product-text">
<div class="product-name">Товар 1</div>
<span class="quantity">3 × <span class="amount">360.000 руб.</span></span>
</div>
</li>
<li>
<a href="#">
<img width="60" height="60" src="#" class="attachment-60x60 wp-post-image" alt="item-2">
</a>
<div class="product-text">
<div class="product-name">тОВАР 2</div>
<span class="quantity">3 × <span class="amount">150.000 руб.</span></span>
</div>
</li>
</ul>
<!-- end product list -->
</li>
|
ligisayan,
attr('href') у вас везде # ???product_name= "#" |
Цитата:
|
ligisayan,
строка 4 не на своём месте Цитата:
строка 17 скрипта отсутствует в html указанный элемент (".shopping-button .amount"). да и непонятно что делают строки 12 - 16 - извлекают цифру? -- а если неизвлекут? i немноговато ? |
Цитата:
строка 17 - добавил недостающий элемент 12-16 - да, извлекают и перезаписывают потом сюда:
$(this).parents('#shopping-button').find(".shopping-button .amount").text((basePrice * number) + " руб.");
|
ligisayan, изменить количество в одном из инпутов - нажать купить под ним
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<meta charset="utf-8">
<style type="text/css">
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function() {
var product_name, number;
$("body").on("added_to_cart", function() {
var arr = [];
$("#shopping-button .cart_list li").each(function(i) {
var span = $(this).find("span.quantity");
arr[i] = span.text().match(/\d+(?:\.\d+)?/g);
if ($(this).find("a").attr("href") == product_name) {
arr[i][0] = number;
span.html(arr[i][0] + "\u00d7 <span class='amount'>" + arr[i][1] + " \u0440\u0443\u0431.</span>");
$(this).parents("#shopping-button").find(".shopping-button .amount").text((arr[i][0] * arr[i][1]).toFixed(3) + " руб.")
}
})
});
$(".add_to_cart_button").click(function(event) {
event.preventDefault();
number = $(this).parents(".product-frame ").find(".input-text.qty.text").val();
product_name = $(this).parents(".product-frame ").find(".product-section h3 a").attr("href");
$("body").trigger("added_to_cart")
})
});
</script>
</head>
<body> <!-- Добавление товара в корзину -->
<div class="product-frame ">
<div class="content-description">
<div class="product-section">
<h3><a href="Товар 1">Товар 1</a></h3>
<table class="description-table">
<tbody>
<tr>
<td class="product-quantity">
<div class="quantity buttons_added">
<input type="number" step="1" min="1" max="27" id="num_count" name="quantity" value="1" title="Кол." class="input-text qty text" size="4">
<input type="button" value="+1" id="button_plus" class="plus">
<input type="button" value="-1" id="button_minus" class="minus">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="process-section">
<div class="price"><span class="amount" baseprice="360000">1.080.000 руб.</span>
</div>
<a href="#" rel="nofollow" data-product_id="3295" data-quantity="1" class="button add_to_cart_button">Купить</a>
</div>
</div>
<div class="product-frame ">
<div class="content-description">
<div class="product-section">
<h3><a href="Товар 2">Товар 2</a></h3>
<table class="description-table">
<tbody>
<tr>
<td class="product-quantity">
<div class="quantity buttons_added">
<input type="number" step="1" min="1" max="27" id="num_count" name="quantity" value="1" title="Кол." class="input-text qty text" size="4">
<input type="button" value="+1" id="button_plus" class="plus">
<input type="button" value="-1" id="button_minus" class="minus">
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="process-section">
<div class="price"><span class="amount" baseprice="360000">1.080.000 руб.</span>
</div>
<a href="#" rel="nofollow" data-product_id="3295" data-quantity="1" class="button add_to_cart_button">Купить</a>
</div>
</div>
<!-- Сама корзина -->
<li id="shopping-button">
<a class="shopping-button" href="#">
<b><span class="amount">360.000 руб.</span></b>
</a>
<ul class="cart_list ">
<li>
<a href="Товар 1">
<img width="60" height="60" src="#" class="attachment-60x60 wp-post-image" alt="item-1">
</a>
<div class="product-text">
<div class="product-name">Товар 1</div>
<span class="quantity">3 × <span class="amount">360.000 руб.</span></span>
</div>
</li>
<li>
<a href="Товар 2">
<img width="60" height="60" src="#" class="attachment-60x60 wp-post-image" alt="item-2">
</a>
<div class="product-text">
<div class="product-name">Товар 2</div>
<span class="quantity">3 × <span class="amount">150.000 руб.</span></span>
</div>
</li>
</ul>
<!-- end product list -->
</li>
</body>
</html>
|
| Часовой пояс GMT +3, время: 21:31. |