Django项目中jQuery无法设置textContent,增减及更新按钮失效求助
Django购物车增减/更新按钮失效问题排查与修复
在Django项目的购物车页面中,通过{% for %}循环生成商品项的增减按钮(+/-)和更新按钮,但点击这些按钮时完全没有响应或功能异常。尝试通过按钮名称+{{product.id}}的方式给元素分配唯一ID来区分,但问题依然存在。
原Django模板代码
<!-- start loop --> {% for item in cart %} <!-- assign product variable --> {% with product=item.product %} <br> <div class="row mb-4 border product-item"> <div class="col-md-3 col-lg-2 order-md-first bg-light"> <img class="img-fluid mx-auto d-block" width="200px" alt="Responsive image" src="{{ product.image.url }}"> <!-- Product image --> </div> <div class="col-md-9 col-lg-10 ps-md-3 ps-lg-10"> <a href="{{ product.get_absolute_url }}" class="text-info text-decoration-none"> <h1 class="h5 pt-2"> {{ product.title }} </h1> </a> <div class="border"> <div class="col border-bottom"> <div class="row p-3"> <div class="col-6"> Product </div> <div class="col-6 text-end"><span class="h6 fw-bold">$ {{ product.price|mul:item.qty}} </span></div> </div> </div> <div class="col"> <div class="row p-3"> <div class="col-12"> <button type="button" id="qty-decrease-button{{product.id}}" data-index="{{product.id}}" class="btn btn-primary btn-sm increase-button"> - </button> <label id = "qty-show{{product.id}}" data-index="{{product.id}}" > {{item.qty}} </label> <button type="button" id="qty-increase-button{{product.id}}" data-index="{{product.id}}" class="btn btn-primary btn-sm decrease-button"> + </button> <br> <br> <button type="button" data-index="{{product.id}}" class="btn btn-primary btn-sm update-button"> Update </button> <button type="button" data-index="{{ product.id }}" class="btn btn-danger btn-sm delete-button"> Delete </button> </div> </div> </div> </div> </div> </div> {% endwith %} {% endfor %}
原JavaScript代码
// Update button $(document).on('click', '.update-button', function (e) { e.preventDefault(); var theproductid = $(this).data('index'); $.ajax({ type: 'POST', url: '{% url "cart-update" %}', data: { product_id: $(this).data('index'), product_quantity: $('#qty-show' + theproductid).text(), csrfmiddlewaretoken: "{{csrf_token}}", action: 'post' }, success: function (json) { // reload page location.reload(); // update cart document.getElementById("cart-qty").textContent = json.qty // update subtotal document.getElementById("total").textContent = json.total }, error: function (xhr, errmsg, err) {} }); }) <!-- Increment-Decrement buttons function --> <script> $(document).on('click', '.increase-button', function (e) { var theproductid = $(this).data('index'); var counter = $('#qty-show' + theproductid); x = counter.textContent; counter.textContent = ++x; }) $(document).on('click', '.decrease-button', function (e) { var theproductid = $(this).data('index'); var counter = $('#qty-show' + theproductid); x = counter.textContent; if (x<=1) { counter.textContent = 1; } else { counter.textContent = --x; } }) </script>
问题排查
- 类名绑定错误:减号按钮(-)用了
increase-button类,加号按钮(+)用了decrease-button类,导致点击逻辑完全错位。 - 文本内容含空白字符:
$('#qty-show' + theproductid).text()会获取标签内的空格、换行等空白字符,转数字时出现NaN,导致AJAX参数无效。 - AJAX回调逻辑错误:
location.reload()会立即刷新页面,后续DOM更新代码永远不会执行。 - CSRF令牌写法问题:直接用
"{{csrf_token}}"可能因模板转义失效,更可靠的方式是从页面隐藏字段获取。
修复后的代码
1. 修正模板中的按钮类名
把减号按钮的increase-button改为decrease-button,加号按钮的decrease-button改为increase-button:
<!-- 修正后的增减按钮 --> <button type="button" id="qty-decrease-button{{product.id}}" data-index="{{product.id}}" class="btn btn-primary btn-sm decrease-button"> - </button> <label id = "qty-show{{product.id}}" data-index="{{product.id}}" > {{item.qty}} </label> <button type="button" id="qty-increase-button{{product.id}}" data-index="{{product.id}}" class="btn btn-primary btn-sm increase-button"> + </button>
2. 修正JavaScript逻辑
// 更新按钮逻辑 $(document).on('click', '.update-button', function (e) { e.preventDefault(); var theproductid = $(this).data('index'); // 去除文本空白并转成数字 var qty = parseInt($('#qty-show' + theproductid).text().trim(), 10); // 从页面隐藏CSRF字段获取令牌 var csrfToken = $('input[name="csrfmiddlewaretoken"]').val(); $.ajax({ type: 'POST', url: '{% url "cart-update" %}', data: { product_id: theproductid, product_quantity: qty, csrfmiddlewaretoken: csrfToken, action: 'post' }, success: function (json) { // 先更新DOM,如需全页刷新放在最后 document.getElementById("cart-qty").textContent = json.qty; document.getElementById("total").textContent = json.total; // location.reload(); // 按需开启 }, error: function (xhr, errmsg, err) { console.error(errmsg, err); // 添加错误日志便于调试 } }); }) // 增减按钮逻辑 <script> $(document).on('click', '.increase-button', function (e) { var theproductid = $(this).data('index'); var counter = $('#qty-show' + theproductid); var x = parseInt(counter.text().trim(), 10); counter.text(++x); }) $(document).on('click', '.decrease-button', function (e) { var theproductid = $(this).data('index'); var counter = $('#qty-show' + theproductid); var x = parseInt(counter.text().trim(), 10); if (x <= 1) { counter.text(1); } else { counter.text(--x); } }) </script>
3. 确保页面存在CSRF隐藏字段
在模板的<form>内或页面头部添加CSRF字段(若未添加):
{% csrf_token %}
内容的提问来源于stack exchange,提问作者bailofwZ
相关产品推荐
相关产品推荐

