使用按钮 f 增加和减少数量



我需要向按钮添加函数。我试图将其添加到 php 文件中。

脚本在这里:


$(document).ready(function(){
$document.on('click','#minus_button',function(){
selected=$(this.attr("data-id"));
quantity = parseInt($('#quantity[data-id="'+selected'"]').val());
$('#quantity[data-id="'+selected'"]').val(quantity -1);

});
$document.on('click','#plus_button',function(){
selected=$(this.attr("data-id"));
quantity = parseInt($('#quantity[data-id="'+selected'"]').val());
$('#quantity[data-id="'+selected'"]').val(quantity + 1);
});
});

这是按钮:


<button type="button" class="btn bg-light border rounded-circle" id="minus_button" data-id="$productid"><i class="fas fa-minus"></i></button>
<input type="text" value="1" class="form-control w-25 d-inline" id="quantity" data-id="$productid">
<button type="button" class=" btn bg-light border rounded-circle"id="plus_button" data-id="$productid"><i class="fas fa-plus"></i></button>

我从数据库中获取product_id。按钮不起作用。如果你能帮忙,我会很高兴的。

您当前的jquery代码有很多语法错误,我已经纠正了。另外,我在这里没有使用idclass因为您可能有很多具有相同ID的按钮。

$(document).ready(function() {
$(document).on('click', '.minus_button', function() {
selected = $(this).attr("data-id");
quantity = parseInt($('.quantity[data-id="' + selected + '"]').val());
$('.quantity[data-id="' + selected + '"]').val(quantity - 1);
});
$(document).on('click', '.plus_button', function() {
selected = $(this).attr("data-id");
quantity = parseInt($('.quantity[data-id="' + selected + '"]').val());
$('.quantity[data-id="' + selected + '"]').val(quantity + 1);
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<!--added class="minus_button"-->
<button type="button" class="btn bg-light border rounded-circle minus_button" id="minus_button" data-id="$productid"><i class="fa fa-minus"></i></button>
<!--added class="quantity"-->
<input type="text" value="1" class="form-control w-25 d-inline quantity" id="quantity" data-id="$productid">
<!--added class="plus_button"-->
<button type="button" class=" btn bg-light border rounded-circle plus_button" id="plus_button" data-id="$productid"><i class="fa fa-plus"></i></button>

还有那个脚本来计算总价。但是以这种方式,我需要在上面添加数量。当我试图添加它不起作用时。

<?php
$total = 0;
if (isset($_SESSION['cart'])){
$product_id = array_column($_SESSION['cart'], 'product_id');
$result = $db->getData();
while ($row = mysqli_fetch_assoc($result)){
foreach ($product_id as $id){
if ($row['id'] == $id){
cartElement($row['product_image'], $row['product_name'],$row['product_price'], $row['id']);
$total = $total + (int)$row['product_price'];
}
}
}
}else{
echo "<h5>Cart is Empty</h5>";
}
?>

最新更新