Django模板{% for %}循环渲染Modal点击仅显示首个商品数据如何解决
问题核心原因
你在Django的for循环中重复生成了相同的id属性,HTML规范要求同一页面内id必须唯一,使用$("#mySizeChartModal")选择元素时,jQuery只会匹配页面中第一个出现的对应id元素,因此无论点击哪个商品的按钮,都只会弹出第一个商品的信息。
修复方案(两种可选,推荐第二种)
方案1:给每个弹窗生成唯一id
修改Django模板中的循环部分,给每个按钮和弹窗的id加上商品ID后缀,避免重复:
<div class="row"> {% for product in page.object_list %} <div class="col-lg-3"> <img class="thumbnail update-wishlist " style="height: auto" src="{{product.finalimagelink}}"> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <!-- 去掉固定id,新增data属性关联对应弹窗 --> <a class="button price-btn" style="vertical-align:middle" data-modal-target="modal_{{product.id}}"> <span>Prices</span> </a> <!-- id加上商品id后缀,保证唯一 --> <div id="modal_{{product.id}}" class="ebcf_modal"> <div class="ebcf_modal-content"> <span class="ebcf_close">×</span> <p>{{product.name}} FROM {{product.store}} £{{product.price}}</p> </div> </div> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-wishlist" style="width:50px;"> <img class="button-image" src="{% static 'images/add.png' %}"> </button> <h4 style="display: inline-block; float: right"><strong>£{{product.price}}</strong></h4> </div> </div> {% endfor %} </div>
修改对应的JavaScript代码:
// 点击按钮时获取关联的弹窗id,显示对应弹窗 $(".price-btn").click(function() { const targetModal = $(this).data('modal-target'); $(`#${targetModal}`).show(); }); // 点击关闭按钮时,隐藏当前所属的弹窗 $(".ebcf_close").click(function() { $(this).closest('.ebcf_modal').hide(); });
方案2:使用全局公共弹窗(推荐,性能更优)
不需要循环生成多个重复的弹窗DOM,仅用一个全局弹窗,点击按钮时动态填充对应商品数据即可:
- 先在循环外的页面任意位置放置全局弹窗:
<!-- 全局价格弹窗,放在for循环外部 --> <div id="globalPriceModal" class="ebcf_modal"> <div class="ebcf_modal-content"> <span class="ebcf_close">×</span> <p id="modalContent"></p> </div> </div>
- 修改循环内的按钮,新增data属性存储当前商品的信息,删掉循环内原来的modal代码:
<a class="button price-btn" style="vertical-align:middle" data-name="{{product.name}}" data-store="{{product.store}}" data-price="{{product.price}}"> <span>Prices</span> </a>
- 修改JavaScript代码:
$(".price-btn").click(function() { // 从当前点击的按钮获取商品信息,填充到弹窗 const name = $(this).data('name'); const store = $(this).data('store'); const price = $(this).data('price'); $('#modalContent').text(`${name} FROM ${store} £${price}`); $('#globalPriceModal').show(); }); $(".ebcf_close").click(function() { $('#globalPriceModal').hide(); });
内容的提问来源于stack exchange,提问作者need_halp
相关产品推荐
相关产品推荐

