使用 jquery 在 django 内部循环中更新计数器的问题
problem with updating counter with jquery inside loop with django
一切正常,除了单击递增或递减按钮时,只有购物车上的最后一个产品被更新!!!,对于其他购物车,我可以手动更新值并单击它会更新的按钮而无需任何问题!!!
这是 django
中 .html 的代码
{% for item in cart %}
<div class="card rounded-3 mb-4 ">
<div class="card-body p-4">
<div class="row d-flex justify-content-between align-items-center">
<div class="col-md-2 col-lg-2 col-xl-2">
<img
src="{{ item.product.product_image.url }}"
class="img-fluid rounded-3" alt="Cotton T-shirt">
</div>
<div class="col-md-3 col-lg-3 col-xl-3">
<p class="lead fw-normal mb-2">{{ item.product.name }}</p>
<p><span class="text-muted">
{% if item.product.is_service %}
Service
{% else %}
Product
{% endif %}
</span> <span class="text-muted">
</div>
<div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data">
<input type="hidden" value="{{ item.product_id }}" class="prod_id">
{% csrf_token %}
{% if item.product.is_service == False %}
{% if item.product.quantity >= item.product_quantity %}
<div class="container">
<div class="row">
<div class="col-lg-2">
<div class="input-group">
<span class="input-group-btn">
<button type="button" id="quantity-left-minus"
class=" changeQuantity btn btn-primary btn-number"
data-type="minus">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="number" id="quantity"
class=" align-items-center qty-input"
value="{{ item.product_quantity }}">
<span class="input-group-btn">
<button type="button" id="quantity-right-plus"
class=" changeQuantity btn btn-primary btn-number"
data-type="plus">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</div>
</div>
{% else %}
<h3>Out of Stock</h3>
{% endif %}
{% endif %}
</div>
<div class="col-md-3 col-lg-2 col-xl-2 offset-lg-1">
<h5 class="mb-0">$ {{ item.product.selling_price }}</h5>
</div>
<div class="col-md-1 col-lg-1 col-xl-1 text-center">
<a href="#!" class="text-danger delete-cart-item">Remove</a>
</div>
</div>
</div>
</div>
{% endfor %}
这里 jquery 代码:
$(document).ready(function () {
var quantitiy = 0;
$('#quantity-right-plus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt($('#quantity').val());
// If is not undefined
$('#quantity').val(quantity + 1);
// Increment
});
$('#quantity-left-minus').click(function (e) {
console.log("jjjj")
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt($('#quantity').val());
// If is not undefined
// Increment
if (quantity > 0) {
$('#quantity').val(quantity - 1);
}
});
// change the quantity in the cart
$('.changeQuantity').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val()
var product_qty = $(this).closest('.product_data').find('.qty-input').val()
var token = $('input[name=csrfmiddlewaretoken]').val()
$.ajax({
method: 'POST',
url: '/update_cart/',
data: {
'product_id' : product_id,
'product_qty' : product_qty == null ? 1 : product_qty,
csrfmiddlewaretoken: token
},
success: function(response) {
console.log(response.status)
alertify.success(response.status)
}
})
})
});
这里是 python 代码
def update_cart(request):
if request.method == 'POST':
prod_id = int(request.POST.get('product_id'))
if Cart.objects.filter(user=request.user, product_id=prod_id):
prod_qty = int(request.POST.get('product_qty'))
cart = Cart.objects.get(product_id=prod_id, user=request.user)
cart.product_quantity = prod_qty
cart.save()
return JsonResponse({'status': "Updated Successfully"})
return redirect('/')
这是因为 $('#quantity')
只有 select 页面上具有 #quantity
ID 的最后一个元素。对于每个项目的数量,您在输入元素上具有相同的 id='quantity'
。 $('#quantity')
只会 select 页面上的最后一个输入元素,因为页面上每个 ID 应该只有一个元素,所以它只会获取最后一个元素。页面上有多个具有相同 ID 的元素是错误的,ID 应该是唯一的。
有几种正确的方法可以完成您想要做的事情。一种选择是给每个输入一个唯一的 ID,例如 id='quantity-{{ item.product_id }}'
,然后将数据属性添加到 increment/decrement 按钮,您可以使用它来获取 jQuery 中的产品 ID,因此它知道要更新哪个输入。
像这样更改 right-button、left-button、input-quantity。
<button type="button" id="{{ item.product_id }}-right-plus" class="quantity-right-plus changeQuantity btn btn-primary btn-number" data-type="plus">
<button type="button" id="{{ item.product_id }}-left-minus" class="quantity-left-minus changeQuantity btn btn-primary btn-number" data-type="minus">
<input type="number" id="{{ item.product_id }}-quantity" class="align-items-center qty-input" value="{{ item.product_quantity }}">
并更改 jQuery 代码。
$('.quantity-right-plus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the element ID
const elementId = $('this').attr('id').split('-')[0]
// Get the field name
const quantity = parseInt($(`#{elementId}-quantity`).val());
// If is not undefined
$(`#{elementId}-quantity`).val(quantity + 1);
// Increment
});
$('.quantity-left-minus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the element ID
const elementId = $('this').attr('id').split('-')[0]
// Get the field name
const quantity = parseInt($(`#{elementId}-quantity`).val());
// If is not undefined
// Increment
if (quantity > 0) {
$(`#{elementId}-quantity`).val(quantity - 1);
}
});
一切正常,除了单击递增或递减按钮时,只有购物车上的最后一个产品被更新!!!,对于其他购物车,我可以手动更新值并单击它会更新的按钮而无需任何问题!!!
这是 django
中 .html 的代码{% for item in cart %}
<div class="card rounded-3 mb-4 ">
<div class="card-body p-4">
<div class="row d-flex justify-content-between align-items-center">
<div class="col-md-2 col-lg-2 col-xl-2">
<img
src="{{ item.product.product_image.url }}"
class="img-fluid rounded-3" alt="Cotton T-shirt">
</div>
<div class="col-md-3 col-lg-3 col-xl-3">
<p class="lead fw-normal mb-2">{{ item.product.name }}</p>
<p><span class="text-muted">
{% if item.product.is_service %}
Service
{% else %}
Product
{% endif %}
</span> <span class="text-muted">
</div>
<div class="col-md-3 col-lg-2 col-xl-2 d-flex product_data">
<input type="hidden" value="{{ item.product_id }}" class="prod_id">
{% csrf_token %}
{% if item.product.is_service == False %}
{% if item.product.quantity >= item.product_quantity %}
<div class="container">
<div class="row">
<div class="col-lg-2">
<div class="input-group">
<span class="input-group-btn">
<button type="button" id="quantity-left-minus"
class=" changeQuantity btn btn-primary btn-number"
data-type="minus">
<span class="glyphicon glyphicon-minus"></span>
</button>
</span>
<input type="number" id="quantity"
class=" align-items-center qty-input"
value="{{ item.product_quantity }}">
<span class="input-group-btn">
<button type="button" id="quantity-right-plus"
class=" changeQuantity btn btn-primary btn-number"
data-type="plus">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</div>
</div>
</div>
{% else %}
<h3>Out of Stock</h3>
{% endif %}
{% endif %}
</div>
<div class="col-md-3 col-lg-2 col-xl-2 offset-lg-1">
<h5 class="mb-0">$ {{ item.product.selling_price }}</h5>
</div>
<div class="col-md-1 col-lg-1 col-xl-1 text-center">
<a href="#!" class="text-danger delete-cart-item">Remove</a>
</div>
</div>
</div>
</div>
{% endfor %}
这里 jquery 代码:
$(document).ready(function () {
var quantitiy = 0;
$('#quantity-right-plus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt($('#quantity').val());
// If is not undefined
$('#quantity').val(quantity + 1);
// Increment
});
$('#quantity-left-minus').click(function (e) {
console.log("jjjj")
// Stop acting like a button
e.preventDefault();
// Get the field name
var quantity = parseInt($('#quantity').val());
// If is not undefined
// Increment
if (quantity > 0) {
$('#quantity').val(quantity - 1);
}
});
// change the quantity in the cart
$('.changeQuantity').click(function (e) {
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val()
var product_qty = $(this).closest('.product_data').find('.qty-input').val()
var token = $('input[name=csrfmiddlewaretoken]').val()
$.ajax({
method: 'POST',
url: '/update_cart/',
data: {
'product_id' : product_id,
'product_qty' : product_qty == null ? 1 : product_qty,
csrfmiddlewaretoken: token
},
success: function(response) {
console.log(response.status)
alertify.success(response.status)
}
})
})
});
这里是 python 代码
def update_cart(request):
if request.method == 'POST':
prod_id = int(request.POST.get('product_id'))
if Cart.objects.filter(user=request.user, product_id=prod_id):
prod_qty = int(request.POST.get('product_qty'))
cart = Cart.objects.get(product_id=prod_id, user=request.user)
cart.product_quantity = prod_qty
cart.save()
return JsonResponse({'status': "Updated Successfully"})
return redirect('/')
这是因为 $('#quantity')
只有 select 页面上具有 #quantity
ID 的最后一个元素。对于每个项目的数量,您在输入元素上具有相同的 id='quantity'
。 $('#quantity')
只会 select 页面上的最后一个输入元素,因为页面上每个 ID 应该只有一个元素,所以它只会获取最后一个元素。页面上有多个具有相同 ID 的元素是错误的,ID 应该是唯一的。
有几种正确的方法可以完成您想要做的事情。一种选择是给每个输入一个唯一的 ID,例如 id='quantity-{{ item.product_id }}'
,然后将数据属性添加到 increment/decrement 按钮,您可以使用它来获取 jQuery 中的产品 ID,因此它知道要更新哪个输入。
像这样更改 right-button、left-button、input-quantity。
<button type="button" id="{{ item.product_id }}-right-plus" class="quantity-right-plus changeQuantity btn btn-primary btn-number" data-type="plus">
<button type="button" id="{{ item.product_id }}-left-minus" class="quantity-left-minus changeQuantity btn btn-primary btn-number" data-type="minus">
<input type="number" id="{{ item.product_id }}-quantity" class="align-items-center qty-input" value="{{ item.product_quantity }}">
并更改 jQuery 代码。
$('.quantity-right-plus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the element ID
const elementId = $('this').attr('id').split('-')[0]
// Get the field name
const quantity = parseInt($(`#{elementId}-quantity`).val());
// If is not undefined
$(`#{elementId}-quantity`).val(quantity + 1);
// Increment
});
$('.quantity-left-minus').click(function (e) {
// Stop acting like a button
e.preventDefault();
// Get the element ID
const elementId = $('this').attr('id').split('-')[0]
// Get the field name
const quantity = parseInt($(`#{elementId}-quantity`).val());
// If is not undefined
// Increment
if (quantity > 0) {
$(`#{elementId}-quantity`).val(quantity - 1);
}
});