【发布时间】:2023-03-06 07:44:01
【问题描述】:
Ajax 请求未隐藏添加购物车按钮且未显示删除购物车按钮,当我单击它插入数据库的产品时添加到购物车,但不隐藏并显示从购物车中删除按钮,我认为问题是从选择 $(this).closest('.content').find('div.removefromcart').hide(); 但我不知道
刀片:
js:
<script>
$(document).ready(function() {
$(".addtocart").click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('cart.addtocart') }}",
data:{
'product_id':$(this).data('product-id')
},
type: "post",
success: function(result){
$("#removed").hide();
$("#added").show();
$(this).closest('.content').find('div.removefromcart').hide();
$(this).closest('.content').find('div.removefromcart').show();
}
});
});
});
$( document ).ready(function() {
$(".removefromcart").click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "{{ route('cart.removefromcart') }}",
data:{
'product_id':$(this).data('product-id')
},
type: "get",
success: function(result){
$("#removed").show();
$("#added").hide();
$(this).closest('.content').find('div.addtocart').show();
$(this).closest('.content').find('div.removefromcart').hide();
}
});
});
});
</script>
html:
<div class="card-body">
<div class="content" style="text-align: center">
<span style="color: black;"> {{ $product->title }} </span>
@if (Auth::user())
<button id="" class="btn btn-primary addtocart" data-product-id={{$product->id}} >Add To Cart</button>
@endif
<button id="" style="display: none" class="btn btn-danger removefromcart" data-product-id={{$product->id}}>Remove From Cart</button>
</div>
</div>
【问题讨论】: