在这一段代码中,数据是从 Django 中的后端获取的。我在 Django 中有产品列表,有些有变化,有些没有变化,我的意思是像披萨一样,有小号、中号和大号,每个都有自己的价格。
问题:我希望所有有变化的项目都应该有变化的价格,但这不会发生在后端的前端,价格正在变化。只有列表中的第一种产品更改了价格,但不是全部。(后端工作完全正常,我检查了源代码(
产品列表.html
{% extends "base.html" %}
<script>
{% block jquery %}
function setPrice(){
var price = $(".variation_select option:selected").attr("data-price")
var sale_price = $(".variation_select option:selected").attr("data-sale-price")
if (sale_price != "" && sale_price != "None" && sale_price != null ) {
$("#price").html("<h4>" + sale_price + " <small class='og-price'>" + price + "</small></h4>");
} else {
$("#price").html(price);
}
}
setPrice()
$(".variation_select").change(function(){
setPrice()
})
{% endblock %}
</script>
{% block content %}
<div class="row">
{% for object in object_list %}
<div class="col-sm-6 col-md-4">
{% if object.productimage_set.count > 0 %}
{% for img in object.productimage_set.all %}
<div class="thumbnail">
<img class='img-responsive' src="{{ img.image.url }}" >
{% endfor %}
{% endif %}
<div class="caption">
<h3>{{ object.title }}</h3>
<form id='add-form' method='GET' action="{% url 'cart' %}">
<p id='jquery-message' class='lead'></p>
{% if object.variation_set.count > 1 %}
<h4 id='price'>{{ object.variation_set.first.price }}</h4>
<select name= 'item' class='form-control variation_select'>
{% for vari_obj in object.variation_set.all %}
<option data-sale-price="{{vari_obj.sale_price}}" data-price="{{ vari_obj.price }}" value="{{ vari_obj.id }}">{{ vari_obj }}</option>
{% endfor %}
</select>
{% else %}
<input type="hidden" name='item' value='{{ object.variation_set.first.id }}' />
<h4 id="price">{% if object.variation_set.first.sale_price %}
{{ object.variation_set.first.sale_price }}
<small class="og-price">{{ object.variation_set.first.price }}</small>
{% else %}
{{ object.variation_set.first.price }}
{% endif %}
</h4>
{% endif %}
<p>{{object.description}}</p>
<input class='form-control' type='number' name='qty' value='1' />
<br></br>
<p><input id='submit-btn' type='submit' value='Add to Cart' class="btn btn-primary" />
</p>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
jQuery放在页面底部而不是顶部可能会有所帮助。您正在尝试将事件附加到 DOM 元素 (.variation_select( 的选择触发器,该触发器在该特定时间尚不存在。
函数setPrices中的问题在于它采用类的第一个元素.variation_select
您应该尝试如下方法,以从类.variation_select的所有元素中进行更改:
$(".variation_select").change(function(){
var price = $(this).attr("data-price");
var sale_price = $(this).attr("data-sale-price");
if (sale_price != "" && sale_price != "None" && sale_price != null ) {
$("#price").html("<h4>" + sale_price + " <small class='og-price'>" + price + "</small></h4>");
} else {
$("#price").html(price);
}
});