我只是在foreach循环中获得了一个产品的价值。现在逻辑是这样的,当我得到它将被插入到表单的输入区域的产品数量时,当点击按钮添加到购物车时产品数量将显示在结帐页面中.foreach循环内的代码就像这样
![<div class="cart">
<table class="discount-prices">
<tr>
<?php foreach ($discounts as $discount) { ?>
<td class="discount-price">
<?php echo sprintf($text_discount, $discount\['quantity'\], $discount\['price'\]); ?>
</td>
</tr>
</table>
<div>
<?php echo $text_qty; ?>
<input type="text" name="quantity" size="2" value="<?php echo $discount\['quantity'\]; ?>" />
<input type="hidden" name="product_id" size="2" value="<?php echo $product_id; ?>" />
<input type="button" value="<?php echo $button_cart; ?>" id="button-cart" class="button" />
</div>
<?php } ?>]
正在为该按钮工作的jQuery脚本就像这样
$('#button-cart').bind('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
$('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
}
}
}
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
//$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
setTimeout(opencartpage(),1000);
}
}
});
});
现在问题在于,当我点击第一个添加到购物车按钮时,它将进入结帐页面但是值是5而不是3.您可以在图像中看到(第二张图片)我点击了在第一个按钮上,其值为“3”,但它采用“5”(最后一个值)。
另一个问题是添加到购物车的第一个按钮正在用于结帐页面,但是另外两个用于添加到购物车的按钮根本不起作用。当点击其余两个按钮时没有任何事情发生。那么有人可以帮助我并告诉我这里的错误部分是什么?
更新
使用$('.button-cart')
代替$('#button-cart')
会使所有按钮处于活动状态,这意味着当点击该按钮时它正在处理结帐页面,但它只获取最后一个值5,可以看到在第一张图片中。那么如何解决这个问题?
答案 0 :(得分:0)
不要将jQuery事件绑定到#button-cart,而是使用.button-cart。 CSS对于匹配id很轻松(即它仍然会匹配它们),但是jQuery并不那么宽容 - 它只会将匹配id的事件绑定到DOM中的一个匹配元素。
此外,ajax数据看起来是发送所有.product-info元素,而不仅仅是链接到按钮的元素。这是未经测试的,但尝试类似:
$('#button-cart').bind('click', function() {
$self = $(this);
$.ajax({
...
data: $self.children(...),
...
});