请看一下我的代码here。该页面已部署here。
我正在使用ID price
来指代一件商品的价格。通用jQuery函数会尝试在选择更改时(相对于商品尺寸)更改每件商品的价格,如下所示:
jQuery(document).ready(function(){
jQuery(".variation_select").change(function(){
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);
}
});
});
由于项目及其数据来自后端,并且我有多个项目,因此HTML可以理解地进行复制,因此,我拥有多个具有相同ID的元素。显示商品价格的HTML如下:
<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 style="text-align: center;">{{ 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' style="text-align: center; display: block;">₹ {{ object.variation_set.first.price }}</h4>
<select name= 'item' class='form-control variation_select' style="margin: 0 auto; width: 30%; display: block;">
{% 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>
<br>
{% else %}
<input type="hidden" name='item' value='{{ object.variation_set.first.id }}' />
<h4 id="price" style="text-align: center; display: block;">₹ {% if object.variation_set.first.sale_price %}
{{ object.variation_set.first.sale_price }}
<small style="text-align: center; display: inline-block" class="og-price">₹</small>
<small class="og-price">{{ object.variation_set.first.price }}</small>
{% else %}
{{ object.variation_set.first.price }}
{% endif %}
</h4>
{% endif %}
<p style="text-align: center;">{{object.description}}</p>
<br>
<input class='form-control' type='number' name='qty' value='1' style="text-align: center; margin: 0 auto; width: 30%; display: block;" />
<br>
<p><input id='submit-btn' type='submit' value='Add to Cart' class="btn btn-primary" style="text-align: center; margin: 0 auto; padding: 5% 10%; display: block;" />
</p>
</form>
</div>
</div>
</div>
{% endfor %}
</div>
据我了解,只有第一个项目的价格会发生变化,因为它的第一个具有唯一ID实例的代码块,其余的所有内容都违反了拥有唯一ID的规则。因此,它们的价格不会改变。虽然将它们放在同一个班级中会同时改变价格,但我也不想这样做。我该如何解决这个问题,即我的页面中有多个商品,但仍然能够分别选择其价格?
最佳答案
在更改的函数上,您可以像这样使用jquery“ closest()”。
$(this).closest("#price").html("₹ " + price);
它将获取ID为“ price”的最近的对象并更改其html内容。
希望对您有所帮助。您可以阅读有关jquery closest api文档的更多信息。